Download JSP text

Document related concepts
no text concepts found
Transcript
JavaServer Pages
Some notes from:
the Hans Bergen text
Hunter text
Sebesta text
JSP and XML text
And from tutorial sites on the web
What is a JSP?
• JSP are html pages which contain both static
(like traditional html) and dynamic content.
Content may vary with the client request, identity
or browser type.
• JSP elements are executed by the server and
merged with the page’s static contents and sent
to the client.
• Accessing beans, sharing information between
users and pages and requests are a few
possible JSP actions.
• JSP syntax is also extensible to deal with
application-specific concerns.
Why JSP?
• A number of technologies have arisen to
challenge CGI programming – the only
choice in the early 90s.
• CGI is not efficient. Each incoming
request spawns a new server process. A
script must be loaded, interpreted
(executed) and then disposed. As traffic
increases the problems inherent in this
model worsen.
CGI alternatives
•
•
•
•
•
•
FastCGI
Mod_perl
NSAPI
ISAPI
Java servlets
All these improve on CGI performance but
at the cost of embedding html in the
programming language. This means only
programmers can develop server pages.
JSP
• JSP may contain java code embedded in
the scripting elements, though this is rarely
needed. Too much code in a JSP results
in the same lopsided application
modularization as placing the html in the
servlet.
• Recent innovations in JSP are the
Expression Language (EL) and the
standard tag library (JSTL).
JSP- benefits
• JSP are compiled, not interpreted.
Typically, they are compiled on the first
load and, unless changed, available to
subsequent requests without another
compilation. In conjunction with a
persistent JVM on a JSP-enabled server,
JSP can be delivered very quickly.
Application modularization
• A good breakdown of an internet
application is for JavaBeans to handle
application logic (& datatypes), servlets
can handle input processing, and JSP can
provide the user interface.
JSP power
•
•
1.
2.
3.
4.
5.
6.
JSP are built on the servlet api (they are
actually compiled into servlets)
consequently JSP can access
JDBC
RMI and CORBA
JNDI (java naming and directory interface)
JMS – java message service
JavaMail
Java API for XML registries (JAXR), java API
for XML-rpc (JAX-RPC) and SAAJ (SOAP with
attachments api for java).
ASP vs JSP
• ASP are Microsoft’s popular technology for
developing dynamic sites. The page may
include VB- and J-script. COM (ActiveX)
components written in C++ can handle complex
code. Database access components and more
are included in ASP.
• ASP.NET, the newest version, provides for
dynamic content to be delivered via XML.
• ASP are compiled.
• Reliance on native COM-code components
makes ASP primarily an (MS) windows-platform
solution.
Others
• PHP- an open source scripting language with C style
syntax.
• ColdFusion –Macromedia’s product. XML-type elements
provide active content following CFML (cold-fusionmarkup-language). Database handling, mailservers,
conditional elements (loops) and allows custom
elements to be added using C++ or Java. CFML
extensions are available from third-party vendors.
• Java servlet template engine: A number of template
engines were developed when programmers realized
that embedding the html in the code was not such a
great idea. Web scripting handles the presentation and
servlets handle processing.
JSP design
• To stop your JSP code from becoming a maintenance
nightmare, you will need to think and ask yourself a few
questions.
• What does this page actually do?
• Should I have my JSP page doing the tasks for add, update and
delete? Would it be better to have them done by different JSPs?
• How can I reduce the amount of Java code in the JSP so a web
designer can keep the front-end looking good?
• How do I reuse code done by other developers in my team?
• Has anyone on the Internet already done some of the things I need
to do in my JSP pages?
• If something goes wrong in my application, how will I log the error?
• How can I make my JSP page display text in different languages?
An example: Technologies to
consider
•
•
•
•
•
•
•
•
•
•
If you were writing a Message Board application, you would think of a frontend dynamically showing messages from registered posters, maybe
sending emails to Message Board posters etc.
J2EE technologies that you will probably consider should include:
JSP - used for designing the front end.
JDBC - as the pages for the Message Board are dynamically produced, it
would make sense to store them in a database table. You would use JDBC
to connect and do queries on the database.
JavaMail - used for sending emails via SMTP.
Now depending on the tasks of the Message Board, you might also what to
consider:
Servlets - alternative to JSP. When you want to carry out a task that does
not need a frontend. A Servlet is a special Java class which outputs HTML
via print statements. You could use a Servlet to send the emails (by also
using JavaMail).
JSP or Servlets when developing
J2EE applications?
•
You will probably use Both.
•
JSP will be used for nearly all your front end web interface with minimal
Java code.
•
When you have a form that sends a request to search for results that you
display in an HTML table, you would use a JSP.
•
However, if you were sending out an email, you would use a Servlet. Why?
•
The process of sending an email does not require a fancy frontend. The
sending email process is a reusable service that would be coded in Java
with no need for HTML design.
Why not design the whole
application as Servlets?
•
To answer this question you need to understand the advantages of
using JSP. The whole point of using JSP was to quickly produce
web front ends. If you wrote an entire web front end application
using servlets, it would probably take you much longer than using
JSP. This is because every element of the HTML page would need
to be in print statements in a Servlet.
• How can we decide between JSP and Servlets?
• It really comes down to analysing and designing your application.
You need to highlight areas that are more like services (without
being fixed to a front end) and other parts that consist of the user's
interface.
The problem with servlets
• Servlets often contain request processing,
business logic and code (println) to generate the
html response.
• Servlet creators must be java programmers.
• Changing look/feel of a web app or upgrading to
support new clients is hard if the GUI features
are in the servlet.
• It is very hard to use web tools to develop an
interface since the resulting html must still be
manually hard-coded into the servlet.
How JSP helps
• JSP can handle the presentation side and
servlets can handle processing.
• One part of the application can be
upgraded/changed without impact to other
parts.
• This modularization enhances portability,
maintainability and re-usability of the
application and its components.
JSP advantage
• JSP supports both scripting and element-based
dynamic content.
• JSP are compiled (efficient).
• JSP can work with servlets which can handle the
logic and processing.
• JSP is a specification, not a product.
Competition in providing JSP can improve
performance and keep JSP around awhile.
• JSP is part of J2EE so JSP have the java API to
back them up and are scalable.
To run JSP text examples
• Install Tomcat
• Examples from O’Reilly’s JSP text (source
code and directories) can be downloaded
from:
http://examples.oreilly.com/jserverpages3/
• Hall text has text website and jsp
examples not included in this ppt so far
Copy ORA directory of extraction into
tomcat webapps --- mine is at
http://CSCI345.oneonta.edu:8080/ora
A JSP technology overview
• see Resources for links to additional JSP technology information.
• In the traditional sense, JSP pages look very much like HTML
pages, with a few extra tags. These tags allow the designer to
embed Java code (not merely JavaScript) in the page itself. A Web
application server will intercept requests for JSP pages. It's tipped
off to their existence by the page's extension: .jsp (not .html). The
Web application server then preprocesses the JSP page, taking out
the JSP tags and any embedded Java code, leaving only the HTML.
The extracted JSP tags and embedded Java code are used to build
a Java servlet (JSP page servlet) that runs the code and inserts the
results back into the original page where the JSP tags used to be.
The result is pure HTML. The Java is stripped out and run on the
server before the requesting browser sees any result.
Steps to execute JSP
1.
2.
3.
4.
5.
6.
7.
8.
9.
The user goes to a web site made using JSP. The user goes to a
JSP page (ending with .jsp). The web browser makes the request
via the Internet.
The JSP request gets sent to the Web server.
The Web server recognizes that the file required is special (.jsp),
therefore passes the JSP file to the JSP Servlet Engine.
If the JSP file has been called the first time, the JSP file is parsed,
otherwise go to step 7.
The next step is to generate a special Servlet from the JSP file. All
the HTML required is converted to println statements.
The Servlet source code is compiled into a class.
The Servlet is instantiated, calling the init and service methods.
HTML from the Servlet output is sent via the Internet.
HTML results are displayed on the user's web browser.
Some URLs with resources
• Some sites I found just searching:
– http://java.sun.com/products/jsp/html/JSPXML
.html
– http://www.onjava.com/pub/a/onjava/2001/11/
28/jsp_xml.html
– http://www.visualbuilder.com/jsp/tutorial/
where to put them
• put jsp into a webapp root directory.
• I copied them into a directory called my-jsp
• They need no servlet tags or url patterns
in the web.xml and so are available for use
as soon as they are copied
• They are compiled into a “workhorse”
servlet, so the first call will be slow.
File Structure: tag libraries and jar
files
• Place jar files (if you’ve created these) in lib and
place class files for compiled java in classes.
Client browsers can’t see or access this code.
• Tag libraries can be placed in lib (in jar format).
• Classes needed can go in classes, following the
same hierarchical/derivation structure they have.
• Alternatively, these files can be zipped and
placed in a war file.
File Structure and your own JSP
• Create your own jsp directory under
webapps in Tomcat.
• Place the *.jsp in subdirectories or directly
in this directory.
• Create a WEB-INF directory in this
directory and a lib directory in here. Copy
standard.jar, jstl.jar and other necessary
tag libraries into lib.
Standard jsp/servlet File Structure
• Tomcat
• webapps
– Your jsp/servlet directory
• Jsp files here or in subdirectories
• WEB-INF directory
» lib (put jar files here, including standard.jar, jstl.jar,…)
» classes (put class files here)
Notes and examples from Hunter
chapter 18 servlets text
hello1.jsp
<HTML>
<HEAD><TITLE>Hello</TITLE></HEAD>
<BODY>
<H1>
<%
if (request.getParameter("name") == null) {
out.println("Hello World");
}
else {
out.println("Hello, " + request.getParameter("name"));
}
%>
</H1>
</BODY></HTML>
hello1.jsp
scriplets and other code in the jsp
• the request for a jsp causes a java compile
creating a servlet which is returned for the
response.
• scriptlets have <% open tag and %> close tag
and contain servlet code.
• declarations begin with <%! and end with %>
• comments have <%-- tags --%>
• assignments/expressions have the form
<%=foo%>
hello2
hello2.jsp
<%-- hello2.jsp --%>
<HTML>
<HEAD><TITLE>Hello</TITLE></HEAD>
<BODY>
<H1>
Hello, <%= getName(request) %>
</H1>
</BODY>
</HTML>
<%!
private static final String DEFAULT_NAME = "World";
private String getName(HttpServletRequest req) {
String name = req.getParameter("name");
if (name == null)
return DEFAULT_NAME;
else
return name;
}
%>
declarations
• declarations should contain any code that
goes outside a servlet’s service methods.
• you may declare static or instance
variables or define new methods.
• hello2.jsp defines a getName() method
and an expression to print it.
directives
• directives enable a jsp to have the
workhorse (background) servlet set
content-type, import a package, set the
buffer size, flush the buffer or throw an
ioexception when the buffer is filled.
Directives also enable a jsp to access user
session information.
• Error-maker throws an exception, errortaker displays an error.
errorMaker.jsp hands error info to errorTaker
Avoid java code in your jsp
• scriptlets, expressions and declarations
allow the placement of java code in jsp.
• Text recommends AVOIDING their use
• tag libraries and java beans facilitate
separation of presentation and content.
beans – a slightly modified
example from the text
package beanex.example;//note package
public class HelloBean {
private String name = "World";
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
beans
• the bean will have to go in the appropriate
file under classes.
• in this case classes/beanex/example
hello3.jsp
<%-- hello3.jsp --%>
<%-- page import="HelloBean“… note this is a comment --%>
<jsp:useBean id="hello" class="beans.HelloBean">
<jsp:setProperty name="hello" property="*" />
</jsp:useBean>
<HTML>
<HEAD><TITLE>Hello</TITLE></HEAD>
<BODY>
<H1>
Hello, <jsp:getProperty name="hello" property="name" />
</H1>
</BODY>
</HTML>
same as two previous examples
and with a parameter
Another jsp/bean example running
the form
<HTML>
<BODY>
<FORM METHOD=POST ACTION="SaveFormData.jsp">
Enter your name : <INPUT TYPE=TEXT NAME=userName
SIZE=20><BR>
Enter a password : <INPUT TYPE=PASSWORD
NAME=userPass SIZE=20><BR>
Enter PIN : <INPUT TYPE=TEXT NAME=userPIN SIZE=4>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
saveform.jsp
saveform.jsp
<jsp:useBean id="user" class="certy.example.UserInfoBean"
scope="session" />
<jsp:setProperty name="user" property="*"/>
<HTML>
<BODY>
<A HREF="DisplayFormData.jsp">Display Entered Data.</A>
</BODY>
</HTML>
DisplayForm.jsp
DisplayForm.jsp
<jsp:useBean id="user" class="certy.example.UserInfoBean"
scope="session"/>
<HTML>
<BODY>
You entered : <BR/>
Name: <%= user.getUserName() %><BR/>
Password: <jsp:getProperty name="user" property="userPass" /><BR/>
PIN: <%= user.getUserPIN() %><BR/>
</BODY>
</HTML>
the bean
package certy.example;
public class UserInfoBean {
String username;
String password;
int pin;
public void setUserName( String value )
{
username = value; }
public void setUserPass( String value )
{
password = value; }
public void setUserPIN( int value )
{
pin = value; }
public String getUserName() { return username; }
public String getUserPass() { return password; }
public int getUserPIN() { return pin; }
}
Creating another form
(example off internet tutorial – I think)
• Here we show how to create and process
an html form.
Copy the code (next slide) and place in a
file named: myform.jsp
Go to myform.jsp in your browser
You will see the form you just created.
It won't do anything yet.
Myform.jsp
<html>
<head>
<!-- Example -->
<title>A Form Example</title>
</head>
<body>
<form action="myformconfirm.jsp" method="post">
Enter in a website name:<br>
<input type="text" name="website"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
Processing a Form
• Here we show how to process the html
form your just created.
Copy the code below and place in a file
named: myformconfirm.jsp
Go to myform.jsp
Fill in some details and submit the form
You should see the results of your
submission
Myformconfirm.jsp processes myform
<html>
<head>
<!-- Example4 -->
<title>myformconfirm</title>
</head>
<body>
<font face=verdana size=3>
Your info has been received:
<br><br>
<%
String sName = request.getParameter("website");
out.print(sName);
%>
</font>
</body>
</html>
myform
Processing myform
Fullform.jsp in notes
Fullformconfirm.jsp in notes
• When you run fullform, and fill in fields,
fullformconfirm will acknowledge data entry
Beans
• The useBean action gives the bean a
name and the getProperty action can be
used to insert a property value directly into
your JSP. Here it is the src attribute from
an html <img> element. The way this
bean works, a new cartoon is loaded on
each access.
Beans & JSP, another example:
The
java
(bean)
class
package beanex;
public class UserData {
String username;
String email;
int age;
public UserData(){
username="xyz";email="[email protected]";age=21;}
public void setUsername( String value )
{
username = value; }
public void setEmail( String value )
{ email = value; }
public void setAge( int value ){age = value;}
public String getUsername() { return username; }
public String getEmail() { return email; }
public int getAge() { return age; }}
JavaBeans
A Javabean is a special type of class that has a number of methods. The JSP page can
call these methods so can leave most of the code in these Javabeans. For example,
if you wanted to make a feedback form that automatically sent out an email. By
having a JSP page with a form, when the visitor presses the submit button this sends
the details to a Javabean that sends out the email. This way there would be no code
in the JSP page dealing with sending emails (JavaMail API) and your Javabean could
be used in another page (promoting reuse).
To use a Javabean in a JSP page use the following syntax:
<jsp : usebean id = " ...." scope = "application" class = "com..." />
The following is a list of Javabean scopes:
page - valid until page completes.
request - bean instance lasts for the client request
session - bean lasts for the client session.
application - bean instance created and lasts until application ends.
About the java
• It is a bean:
– it has a default constructor
– get/set methods for the fields
• Belongs to a package (beanex)
Index.html to get us started
<html>
<body>
Welcome, <A HREF="GetName.html">Start
here</A>
</body>
</html>
Getname.html --- a form
•
•
•
•
•
•
•
•
•
•
<HTML>
<BODY>
<FORM METHOD=POST ACTION="SaveName.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username
SIZE=20><BR>
What's your e-mail address? <INPUT TYPE=TEXT NAME=email
SIZE=20><BR>
What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
A savename.jsp which uses a bean
<jsp:useBean id="user" class="beanex.UserData"
scope="session"/>
<jsp:setProperty name="user" property="*"/>
<HTML>
<BODY>
<A HREF="NextPage.jsp">Continue</A>
</BODY>
</HTML>
The java bean
package certy.example;
public class UserInfoBean {
String username;
String password;
int pin;
public void setUserName( String value )
{
username = value; }
public void setUserPass( String value )
{
password = value; }
public void setUserPIN( int value )
{
pin = value; }
public String getUserName() { return username; }
public String getUserPass() { return password; }
public int getUserPIN() { return pin; }}
Nextpage.html which uses the
same bean
<jsp:useBean id="user" class="beanex.UserData"
scope="session"/>
<HTML>
<BODY>
You entered<BR>
Name: <%= user.getUsername() %><BR>
Email: <%= user.getEmail() %><BR>
Age: <%= user.getAge() %><BR>
</BODY>
</HTML>
deployment
• In webapps place a directory for this application.
(I called mine getnamebean).
Deployment continued
• Drop the html and jsp files into this
directory.
• The directory images is empty and METAINF contains a manifest which can be
omitted.
Deployment continued: WEB-INF
contents
SaveName
NextPage
More about deployment directories
• Src is optional, it contains the java bean
source.
• Lib is empty, but could contain the jar file
for the class(es) needed.
• Classes contains a directory called
beanex which contains UserData.class
Web.xml is also optional
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
<web-app>
<!– this is a comment: no special configuration required -->
</web-app>
FormBean:display form
•
•
•
•
•
•
•
•
•
•
<HTML>
<BODY>
<FORM METHOD=POST
ACTION="SaveFormData.jsp">
Enter your name : <INPUT
TYPE=TEXT NAME=userName
SIZE=20><BR>
Enter a password : <INPUT
TYPE=PASSWORD
NAME=userPass SIZE=20><BR>
Enter PIN : <INPUT TYPE=TEXT
NAME=userPIN SIZE=4>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
A do-nothing jsp
<jsp:useBean id="user"
class="certy.example.UserInfoBea
n" scope="session" />
<jsp:setProperty name="user"
property="*"/>
<HTML>
<BODY>
<A
HREF="DisplayFormData.jsp">Dis
play Entered Data.</A>
</BODY>
</HTML>
Displaying the data stored in the
bean
•
<jsp:useBean id="user"
class="certy.example.UserInfoBean"
scope="session"/>
•
•
<HTML>
<BODY>
•
•
•
You entered : <BR/>
Name: <%= user.getUserName()
%><BR/>
Password: <jsp:getProperty
name="user" property="userPass"
/><BR/>
PIN: <%= user.getUserPIN() %><BR/>
•
•
</BODY>
</HTML>
•
A variation
Last jsp
The same java bean
package beanex;
public class UserData {
String username;
String email;
int age;
public UserData(){
username="xyz";email="[email protected]";age=21;}
public void setUsername( String value )
{
username = value; }
public void setEmail( String value )
{
email = value; }
public void setAge( int value )
{
age = value; }
public String getUsername() { return username; }
public String getEmail() { return email; }
public int getAge() { return age; }}
Helloworld.jsp
(in root directory of tomcat)
<html>
<head>
<title>My first JSP page
</title>
</head>
<body>
<%@ page language="java" %>
<% out.println("Hello World"); %>
</body>
</html>
Running Hello.jsp
• Place it in an appropriate directory, like
tomcat/root
Text examples page off your
Tomcat server
Click on examples links to run
• http://localhost:8080/ora/ch5/easy.jsp
JSP is as easy as ...
1+2+3=6
Easy.jsp source
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html>
<head>
<title>JSP is Easy</title>
</head> <body bgcolor="white">
<h1>JSP is as easy as ...</h1>
<%-- Calculate the sum of 1 + 2 + 3 dynamically --%>
1+2+3=
<c:out value="${1 + 2 + 3}" />
</body>
</html>
JSP elements
• There are 3 types of elements: directive,
action and scripting. EL (expression
language) might be treated as a fourth
type.
Directives
• JSP begin with a directive indicating page
content type:
<%@ page contentType="text/html" %>
• Text/html, text/plain and text/xml are some
possible attributes.
• The next line of easy.jsp specifies a custom tag
library:
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
• Jsp directives have format <%@ content%> and
are processed at translation time.
Comments
• Comments have the form:
<%-- put comment here --%>
• JSP elements like directives and
comments do not go to the browser.
Template text
• Besides JSP elements, a JSP page may
contain html, xml or any markup language
content. This is called template text and it
is sent to the browser (after compilation of
JSP elements and re-assembly) as is.
• The JSP container doesn’t process or
parse this content.
Action Elements
• A JSP may display shopping cart, search
results, personalized news or bulletin
board messages which are dynamically
generated and specific to a client.
• An action is executed when the page is
requested. (Request processing phase).
• The only action element in easy.jsp is
<c:out value=“${1+2+3}” />
Action Elements
• If the action element has a body, then it will have
an opening tag (possibly with attribute/value
pairs), a body, and a closing tag.
• If there is no body, then shorthand notation can
be used as in the previous example, in a syntax
equivalent to xml.
• The action element has no spaces, and consists
of a prefix:name pair. The prefix is defined in
the tag library directive and is the prefix that will
be used for this library.
• The taglib’s URI is used by the container to find
the information needed for processing.
Action Elements
• There are standard, custom and JSTL actions.
• Standard actions are part of the jsp specification
and require no tag library. (text pg 53 has a
table).
• JSP specification allows for definition of custom
actions as well.
• JSTL is meant to obviate the need for custom
actions for mundane tasks and includes
categories Core (control processing and
imports), XML processinf, internationalization
and ofrmatting, SQL database actions, and
functions.
JSTL EL
• EL start with ${ delimiter and end with }
• Literals, booleans, strings, null keyword
and variables are supported.
• There are a number of EL implicit
variables, too, like pageScope, param,
header. (pg 56 table.)
• Special characters must appear in quotes.
• Variables are typed, as in Java.
Standard operators may appear.
These have some variations:
• / or div
• % or mod
• <= or le
• == or eq
• && or and
• ! or not
• And so on (table in text pg 56-57)
Implicit Objects
So far we know that the developer can create Javabeans and interact
with Java objects. There are several objects that are automatically
available in JSP called implicit objects.
The implicit objects are
Variable Of type Request Javax.servlet.http.httpservletrequest
Response Javax.servlet.http. httpservletresponse Out
Javax.servlet.jsp.JspWriter Session Javax.servlet.http.httpsession
PageContent Javax.servlet.jsp.pagecontext Application
Javax.servlet.http.ServletContext Config
Javax.servlet.http.ServletConfig Page Java.lang.Object
objects
Page object
Represents the JSP page and is used to call any methods defined by
the servlet class.
Config object
Stores the Servlet configuration data.
Request object
Access to information associated with a request. This object is
normally used in looking up parameter values and cookies.
<% String devStr = request.getParameter("dev"); %>
Development language = <%= devStr %>
This code snippet is storing the parameter "dev" in the string devStr.
The result is displayed underneath.
Some examples from text and
tutorials: a loop example
• For the next example, we will make use of
the different tags we have learnt. This
example will declare two variables; one
string used to stored the name of a
website and an integer called counter that
displays the number of times the page has
been accessed. There is also a private
method declared to increment the counter.
The website name and counter value are
displayed.
Jsp example 2
<HTML>
<HEAD>
<!-- Example2 -->
<TITLE> JSP loop</TITLE>
</HEAD>
<BODY>
<font face=verdana color=darkblue>
JSP loop
<BR> <BR>
<%!
public String writeThis(int x)
{
String myText="";
for (int i = 1; i < x; i++)
myText = myText + "<font size=" + i + " color=darkred face=verdana>JSP
Tutorial</font><br>" ;
return myText;
}
%>
This is a loop example from the
<br>
<%= writeThis(8) %>
</font>
</BODY>
</HTML>
Running loop.jsp
Get client’s computer information
<html>
<head>
<!-- Example5 -->
<title>clientinfo.jsp</title>
</head>
<body>
Client computer details:
<br><br>
<b>Ip address</b>:
<br>
<%=request.getRemoteAddr()%>
<br><br>
<b>Computer name</b>:
<br>
<%=request.getRemoteHost()%>
<br><br>
</body>
</html>
Clientinfo.jsp
Tomcat’s example jsp files
Tomcat comes with a number of JSP
examples in a directory:
Web-apps/jsp-examples
These can be run by entering
http://IP:port/jsp-examples/subdir/file.jsp
On my IP/tomcat server, it would be
http://csci345.oneonta.edu:8080/jspexamples/file.jsp
JSP examples on Tomcat
• http://localhost:8080/jspexamples/checkbox/check.html
submit
A get date example:
http://localhost:8080/jspexamples/dates/date.jsp
http://localhost:8080/jspexamples/colors/colrs.jsp
Using Javabeans in J2EE
Design.
If you thought that Javabeans were only
useful in doing Swing Java applications
then you are wrong.
To minimise the (presentation logic) code
in your JSP, Javabeans are used to
produce reusable methods.
The JSP specification provides clear ways
of using Javabeans in JSP pages.
JavaBeans
• JavaBeans are java classes satisfying the
bean specification:
• Must have a no argument constructor
• Package name is recommended
• Properties (fields) are accessed via get()
and set() methods
• Should implement serializable interface
JavaBeans –an example
package something;
public class Name implements java.io.Serializable {
private String theName;
public Name(){theName=“Bob”;}
public void setName(String n){theName=n;}
public String getName(){return theName;}
}
Cartoon JSP using a bean:
http://localhost:8080/ora/ch6/cartoon.jsp
<html> <head>
<title>A dose of Dilbert</title>
</head>
<body bgcolor="white">
<h1>A dose of Dilbert</h1>
<jsp:useBean id="cartoon"
class="com.ora.jsp.beans.motd.CartoonBean" />
<img src="images/<jsp:getProperty
name="cartoon" property="fileName" />">
</body>
</html>
Cartoon.jsp source
<html>
<head>
<title>A dose of Dilbert</title>
</head>
<body bgcolor="white">
<h1>A dose of Dilbert</h1>
<jsp:useBean id="cartoon"
class="com.ora.jsp.beans.motd.CartoonBean" />
<img src="images/<jsp:getProperty name="cartoon"
property="fileName" />">
</body>
</html>
Stealing a JSP example from the text
• http://localhost:8080/my-jsp/cartoon.jsp
• Need to copy images directory and tags from this
chapter examples to my-jsp directory structure.
Using JSP tags
There are four main tags:
•
•
•
•
•
Declaration tag
Expression tag
Directive tag
Scriptlet tag
Action tag
Declaration tag
( <%! %> )
This tag allows the developer to declare variables or methods.
Before the declaration you must have <%!
At the end of the declaration, the developer must have %>
Code placed in this tag must end in a semicolon ( ; ).
Declarations do not generate output so are used with JSP expressions or scriptlets.
For Example,
<%!
private int counter = 0 ;
private String get Account ( int accountNo) ;
%>
Expression tag
( <%= %>)
This tag allows the developer to embed any Java
expression and is short for out.println().
A semicolon ( ; ) does not appear at the end of the code
inside the tag.
For example, to show the current date and time.
Date : <%= new java.util.Date() %>
Directive tag
( <%@ directive ... %>)
A JSP directive gives special information about the page to the JSP
Engine.
There are three main types of directives:
1)
2)
3)
page - processing information for this page.
Include - files to be included.
Tag library - tag library to be used in this page.
Directives do not produce any visible output when the page is
requested but change the way the JSP Engine processes the page.
Directives
• 1.
Page directive
• This directive has 11 optional attributes
that provide the JSP Engine with special
processing information. The following table
lists the 11 different attributes with a brief
description:
•
Include directive
Allows a JSP developer to include contents of a file inside another.
Typically include files are used for navigation, tables, headers and
footers that are common to multiple pages.
Two examples of using include files:
This includes the html from privacy.html found in the include directory
into the current jsp page.
<%@ include file = "include/privacy.html" %>
or to include a naviagation menu (jsp file) found in the current
directory.
<%@ include file = "navigation.jsp" %>
Include files are discussed in more detail in the later sections of this
tutorial.
Tag Lib directive
A tag lib is a collection of custom tags that can be
used by the page.
<%@ taglib uri = "tag library URI" prefix = "tag
Prefix" %>
Custom tags were introduced in JSP 1.1 and
allow JSP developers to hide complex server
side code from web designers.
This topic will be covered in the Advanced JSP
tutorial at visualbuilder.com
Scriptlet tag
( <% ... %> )
Between <% and %> tags, any valid Java code is
called a Scriptlet. This code can access any
variable or bean declared.
For example, to print a variable.
<%
String username = "visualbuilder" ;
out.println ( username ) ;
%>
Action tag
There are three main roles of action tags :
1)
2)
3)
enable the use of server side Javabeans
transfer control between pages
browser independent support for applets.
Text chapter 7
Custom Action for a bean:
classpath environment variable to compile
javax.servlet.jsp classes
C:\xerces-j-bin.2.7.0\xerces2_7_0\xercesimpl.jar;C:\xerces-j-bin.2.7.0\xerces2_7_0\resolver.jar;C:\jakarta-tomcat5.5.10\common\lib\activation.jar;C:\jakarta-tomcat5.5.10\common\lib\mail.jar;c:\program
files\java\jdk1.5.0_03\bin;c:\progra~1\java\jdk1.5.0_03\lib
;C:\Progra~1\Java\jdk1.5.0_03\bin;c:\soap\soap\lib\soap.
jar;C:\jakarta-tomcat-5.5.10\webapps\ROOT\WEBINF\classes;c:\jakart~1.10\common\lib;c:\jakart~1.10\co
mmon\lib\jspapi.jar;c:\jakart~1.10\common\lib\servle~1.jar
Custom Action for a bean:
a simple bean
package beanex2;
public class SomeBean{
String field;
String message;
public SomeBean(){
message="Hello";
field="nobody";
}
public void setField(String x){
field=x;
}
public String getMessage(){
return message+field;}
}
Custom Action for a bean:
java TagHandler class
package beanex2;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class TagExample extends SimpleTagSupport{
private SomeBean sb= new SomeBean();
private String field;
public void setField(String fvalue){
field=fvalue;}
public void doTag() throws IOException{
sb.setField(field);
JspWriter out =getJspContext().getOut();
out.println(sb.getMessage());
}
}
Compile the java files
•
C:\PROGRA~1\JAVA\JDK15~1.0_0\BIN>javac beanex2\TagExample.java
•
C:\PROGRA~1\JAVA\JDK15~1.0_0\BIN>
sample tld files from ora (in notes below also)
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>examples</short-name>
<uri>C:\jakarta-tomcat-5.5.10\webapps\myfolder\WEB-INF\examples</uri>
<description>
A simple tab library for the examples
</description>
<!-- A simple Tag -->
<!-- foo tag -->
<tag>
<name>foo</name>
<tag-class>examples.FooTag</tag-class>
<tei-class>examples.FooTagExtraInfo</tei-class>
<body-content>JSP</body-content>
<description>
Perform a server side action; uses 3 mandatory attributes
</description>
<attribute>
<name>att1</name>
<required>true</required>
</attribute>
<attribute>
<name>att2</name>
<required>true</required>
</attribute>
<attribute>
<name>att3</name>
<required>true</required>
</attribute>
</tag>
</taglib>
Chapter 15 JSP & XML
• You’ll need to copy jstl.jar plus the text’s
tags directory and mytags.tld to
appropriate places in your jsp directory.
A jsp containing xml
• Remember, jsp may contain any markup
language, not just html
• In this example, the jsp contains names,
ids and emails in xml.
• We use an xsl file (import) to generate an
html page from the xml.
Emails_html.jsp
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<html>
<head>
<title>Email List</title>
</head>
<body bgcolor="white">
<c:import url="emailtable.xsl" var="stylesheet" />
<x:transform xslt="${stylesheet}">
<?xml version="1.0" encoding="ISO-8859-1"?>
<students>
<student id="123">
<first-name>Katie</first-name>
<last-name>Higgins</last-name>
<email>HigginKM</email>
</student>
….
</students>
</x:transform>
</body>
</html>
Emailtable.xsl (in notes,too)
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="students">
<table border="1" width="100%">
<tr>
<th>ID</th>
<th>Student Name</th>
<th>Email</th>
</tr>
<xsl:for-each select="student">
<tr>
<td>
<xsl:value-of select="@id"/>
</td>
<td>
<xsl:value-of select="last-name"/>,
<xsl:value-of select="first-name"/>
</td>
<td>
<xsl:value-of select="email"/>
</td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
In tomcat
Another xml/xsl example in jsp
• In the notes I placed a jsp containing xml
markup for the courses I teach (titles,
numbers, and texts)
• I created a stylesheet to traverse this xml
and return course titles, numbers and so
on to populate an html table
Xsl in notes
• See notes below for the stylesheet
http://csci345.oneonta.edu:8080/myfolder/schedule.jsp
Scriptlets: chapter 16
• A random color function:
String randomColor() {
java.util.Random random = new java.util.Random();
int red = (int) (random.nextFloat() * 255);
int green = (int) (random.nextFloat() * 255);
int blue = (int) (random.nextFloat() * 255);
return "#" +
Integer.toString(red, 16) +
Integer.toString(green, 16) +
Integer.toString(blue, 16);
}
A random color jsp: generates an html table with
random colors: entire jsp in notes
<html> <head>
<title>Random Color</title>
</head> <body bgcolor="white">
<h1>Random Color</h1>
<table border="1" width="100%">
<tr>
<td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td>
<td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td>
<td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td>
</tr>
<tr>
<td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td>
<td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td>
<td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td>
</tr> <tr>
<td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td>
<td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td>
<td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td>
</tr> <tr>
<td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td>
<td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td>
<td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td>
</tr>
</table> </body></html>
In tomcat:
http://csci345.oneonta.edu/myfolder/colors.jsp
Init and destroy (see servlet notes) used in a jsp
<%@ page language="java" contentType="text/html" %>
<%@ page import="java.util.Date" %>
<%!
Date orig;
int globalCounter = 0;
public void jspInit(){orig=new Date();}
public void jspDestroy(){
ServletContext context=getServletConfig().getServletContext();
context.log("greeting.jsp visited"+globalCounter+"times between" +orig+"and"+(new
Date()));
}
private String getGreeting() {
Date now = new Date();
String greeting = now.toString();
if (now.getHours() < 12) {
greeting +="Good morning"; }
else if (now.getHours() < 18) {
greeting += "Good day"; }
else {
greeting += "Good evening"; }
return greeting; }
%>
The rest of greeting.jsp
<html>
<head>
<title>Using several techniques</title>
</head>
<body bgcolor="white">
<%= getGreeting() %>
<% if (request.getParameter("name") == null) { %>
stranger!
<% } else { %>
partner!
<% } %>
<p>How are you?</p>
<%
String userAgent = request.getHeader("User-Agent");
if (userAgent.indexOf("MSIE") != -1) {
%>
You're using Internet Explorer.
<% } else if (userAgent.indexOf("Mozilla") != 1) { %>
You're probably using Netscape.
<% } else { %>
You're using a browser I don't know about.
<% } %>
<p>This page has been visited: <%= ++globalCounter %> times since <%= orig %>.</p>
</body>
</html>
csci345.oneonta.edu:8080/myfolder/greeting.jsp