Java Server Pages - notesvillage

fortunabrontideInternet και Εφαρμογές Web

13 Νοε 2013 (πριν από 3 χρόνια και 7 μήνες)

105 εμφανίσεις


MODULE
-
IV

JAVA SERVER PAGES

Java Server Pages

Java Server Pages (JSP) is a technology that lets you mix regular, static HTML with
dynamically
-
generated HTML. Many Web pages that are built by CGI programs are
mostly static, with the dynamic part limited to
a few small locations. But most CGI
variations, including servlets, make you generate the entire page via your program, even
though most of it is always the same. JSP lets you create the two parts separately.

The Advantage of Servlets Over "Traditional" CG
I

Java servlets are more efficient, easier to use, more powerful, more portable, and cheaper
than traditional CGI and than many alternative CGI
-
like technologies.



Efficient

With traditional CGI, a new process is started for each HTTP request. If the CGI p
rogram
does a relatively fast operation, the overhead of starting the process can dominate the
execution time. With servlets, the Java Virtual Machine stays up, and each request is
handled by a lightweight Java thread, not a heavyweight operating system pr
ocess.
Similarly, in traditional CGI, if there are
N

simultaneous request to the same CGI
program, then the code for the CGI program is loaded into memory N times. With
servlets, however, there are
N

threads but only a single copy of the servlet class. Ser
vlets
also have more alternatives than do regular CGI programs for optimizations such as
caching previous computations, keeping database connections open, and the like.



Convenient


Besides the convenience of being able to use a familiar language, servlets

have an
extensive infrastructure for automatically parsing and decoding HTML form data,
reading and setting HTTP headers, handling cookies, tracking sessions, and many other
such utilities.



Powerful


Java servlets easily do several things that are diffic
ult or impossible with regular CGI.
For one thing, servlets can talk directly to the Web server (regular CGI programs can't).
This simplifies operations that need to look up images and other data stored in standard
places. Servlets can also share data amon
g each other, making useful thing like database
connection pools easy to implement. They can also maintain information from request to
request, simplifying things like session tracking and caching of previous computations.





Portable


Servlets are written
in Java and follow a well
-
standardized API. Consequently, servlets
written for, say I
-
Planet Enterprise Server can run virtually unchanged on Apache,
Microsoft IIS, or Web Star. Servlets are supported directly or via a plug
-
in on almost
every major Web ser
ver.



Inexpensive


There are a number of free or very inexpensive Web servers available that are good for
"personal" use or low
-
volume Web sites. However, with the major exception of Apache,
which is free, most commercial
-
quality Web servers are relatively

expensive.
Nevertheless, once you have a Web server, no matter the cost of that server, adding
servlet support to it (if it doesn't come preconfigured to support servlets) is generally free
or cheap.

The separation of user interface and program logic in
a JSP page allows for a very
convenient delegation of tasks between web content authors and developers. It also
allows developers to create flexible code that can easily be updated and reused. Because
JSP pages are automatically compiled as needed, web aut
hors can make changes to
presentation code without recompiling application logic. This makes JSP a more flexible
method of generating dynamic web content than Java servlets, whose functionality Java
Server Pages extend.



JSP and Servlets


Java servlets al
low creating dynamically
-
generated web pages that include data from
server
-
side Java objects. But the servlet approach to generating web pages is to embed
HTML tags and presentation code within a Java class. This means that changes to
presentation code req
uires modification and recompilation of the servlet source file.
Because web authors who design HTML pages may not be the same folks as the
developers who write servlet code, updating servlet
-
based web applications can be an
involved process.

Enter Java Se
rver Pages, which are an extension of the Servlet API. In fact, JSP pages are
compiled into servlets before they are used, so they have all of the benefits of servlets,
including access to Java APIs. Because JSP pages are generally presentation code with
a
pplication logic embedded in them, they can be thought of as "inside
-
out" servlets.

While JSP pages mainly provide a higher
-
level method of creating servlets, they bring
other benefits as well. Advantages of using JSP are:





JSP pages easily combine static
templates, including HTML or XML fragments,
with code that generates dynamic content.




JSP pages are compiled dynamically into servlets when requested, so page authors
can easily make updates to presentation code. JSP pages can also be precompiled if
desi
red.




JSP tags for invoking JavaBeans components manage these components
completely, shielding the page author from the complexity of application logic.





Developers can offer customized JSP tag libraries that page author’s access using
an XML
-
like syntax
.




Web authors can change and edit the fixed template portions of pages without
affecting the application logic. Similarly, developers can make logic changes at the
component level without editing the individual pages that use the logic.

In general, JSP
allows developers to easily distribute application functionality to a wide
range of page authors. These authors do not have to know the Java programming
language or know anything about writing servlet code, so they can concentrate on writing
their HTML cod
e while you concentrate on creating your objects and application logic.

JSP Advantages


Separation of static from dynamic conten
t:

With servlets, the logic for generation of the dynamic content is an intrinsic part of the
servlet itself, and is closely ti
ed to the static presentation templates responsible for the
user interface. Thus, even minor changes made to the UI typically result in there
compilation of the servlet. This tight coupling of presentation and content results in
brittle, inflexible applica
tions. However, with JSP, the logic to generate the dynamic
content is kept separate from the static presentation templates by encapsulating it within
external JavaBeans components. These are then created and used by the JSP page using
special tags and scr
iptlets. When a page designer makes any changes to the presentation
template, the JSP page is automatically recompiled and reloaded into the web server by
the JSP engine.


Write Once Run Anywher
e:

JSP technology brings the "Write Once, Run Anywhere" parad
igm to interactive Web
pages. JSP pages can be moved easily across platforms, and across web servers, without
any changes.


Dynamic content can be served in a variety of format
s:

There is nothing that mandates the static template data within a JSP page to

be of a
certain format. Consequently, JSP can service a diverse clientele ranging from
conventional browsers using HTML/DHTML, to handheld wireless devices like mobile
phones and PDAs using WML, to other B2B applications using XML.



First JSP


JSP simply
puts Java inside HTML
pages. We

can take any existing HTML page and
change its extension to ".jsp" instead of ".html".

What is happening behind the scenes is
that the JSP is being turned into a Java file, compiled and loaded.


This compilation only
happens

once, so after the first load, the file doesn't take long to load anymore.


(But
every time we change the JSP file, it will be re
-
compiled again.)


Ex:

<HTML>


<BODY>




Hello!


Our First JSP


</BODY>


</HTML>


Adding dynamic content via ex
pressions

As in the previous section, any HTML file can be turned into a JSP file by changing its
extension to .jsp.


Of course, what makes JSP useful is the ability to embed Java.


Put the
following text in a file with .jsp extension (let us call it
hello
.jsp
), place it in the JSP
directory, and view it in a browser.





<HTML>

<BODY>


Hello!


The time is now <%= new java.util.Date() %>

</BODY>

</HTML>


Notice that each time we reload the page in the browser; it comes up with the current
time
. The character sequences
<%=

and
%>

enclose Java expressions, which are
evaluated at run time. This is what makes it possible to use JSP to generate dynamic
HTML pages that change in response to user actions or vary from user to user.


JSP Processing

Jus
t as a web server needs a servlet container to provide an interface to servlets, the
server needs a
JSP container

to process JSP pages. The JSP container is responsible for
intercepting requests for JSP pages. To process all JSP elements in the page, the c
ontainer
first turns the JSP page into a servlet (known as the
JSP page implementation class
).


The conversion is pretty straightforward; all template text is converted to
println( )

statements similar to the ones in the hand coded servlet and all JSP elem
ents are
converted to Java code that implements the corresponding dynamic behavior. The
container then compiles the servlet class.


Converting the JSP page to a servlet and compiling the servlet form the
translation
phase
. The JSP container initiates the tr
anslation phase for a page automatically when it
receives the first request for the page. Since the translation phase takes a bit of time, the
first user to request a JSP page notices a slight delay. The translation phase can also be
initiated explicitly;
this is referred to as
precompilation

of a JSP page. Precompiling a
JSP page is a way to avoid hitting the first user with this delay. The JSP container is also
responsible for invoking the JSP page implementation class (the generated servlet) to
process e
ach request and generate the response. This is called the
request

processing
phase
. The two phases are illustrated in the figure given below.





JSP page translation and processing phases



JSP Elements

There are three types of JSP elements:
scripting, directive

and

action


JSP Scripting Elements

JSP scripting elements enable us to insert Java code into the servlet th
at will be generated
from the current JSP page. There are three forms:

1.

Declarations of the form
<%!

code

%>

that are inserted into the body of the
servlet class, outside of any existing methods.

2.

Expressions of the form
<%=

expression

%>

that are evaluate
d and inserted into
the output.

3.

Scriptlets of the form
<%

code

%>

that are inserted into the servlet's
service

method.



Declaration

Declares a variable or method valid in the scripting language used in the JSP page.

JSP Syntax

<%!
declaration;

[ declarati
on;] + ...

%>

Examples

<%! int i = 0; %>

<%! int a, b, c; %>

<%! Circle a = new Circle(2.0); %>

Description

A declaration declares one or more variables or methods that can use in Java code later in
the JSP file. We must declare the variable or method
before

use it in the JSP file.

We can declare any number of variables or methods within one declaration element, as
long as we end each declaration with a semicolon. The declaration must be valid in the
Java programming language.

When we write a declara
tion in a JSP file, remember these rules:



We must end the declaration with a semicolon .We can already use variables or
methods that are declared in packages imported by the
<%@ page %>

directive,
without declaring them in a declaration element.

A declar
ation has translation unit scope, so it is valid in the JSP page and any of its static
includes files. A static include file becomes part of the source of the JSP page and is any
file included with an
<%@ include %>

directive or a static file included with

a
<jsp:
include>

element. The scope of a declaration does not include dynamic files included
with
<jsp: include>
.

Expression

Contains an expression valid in the scripting language used in the JSP page.

JSP Syntax

<%=
expression

%>

Examples

Current time
: <%= new java.util.Date () %>

Description

An expression element contains a scripting language expression that is evaluated,
converted to a
String
, and inserted where the expression appears in the JSP file. Because
the value of an expression is converted t
o a
String
, we can use an expression within a line
of text, whether or not it is tagged with HTML, in a JSP file.


When we write expressions in a JSP file, remember these points:



We cannot use a semicolon to end an expression (however, the same expression

within a scriptlet requires the semicolon).



The expression element can contain any expression that is valid according to the
Java Language Specification
.

We can sometimes use expressions as attribute values in JSP elements. An expression can
be complex
and composed of more than one part or expression. The parts of an
expression are evaluated in left
-
to
-
right order.

Scriptlets

JSP Syntax

<%
code fragment

%>

Examples

<%







String name = null;







if (request.getParameter("name") == null) {

%>

<%
@ include file="error.html" %>


<%







} else {







foo.setName(request.getParameter("name"));







if (foo.getName().equalsIgnoreCase("integra"))







name = "acura";







if (name.equalsIgnoreCase( "acura" )) {

%>


Description

A scriptlet
can contain any number of language statements, variable or method
declarations, or expressions that are valid in the page scripting language.

Within a scriptlet, we can do any of the following:



Declare variables or methods to use later in the file.



Writ
e expressions valid in the page scripting language.



Use any of the implicit objects or any object declared with a
<jsp:useBean>

element.



Write any other statement valid in the scripting language used in the JSP page.

Any text, HTML tags, or JSP elements

must be
outside

the scriptlet.


Scriptlets are executed at request time, when the JSP container processes the client
request. If the scriptlet produces output, the output is stored in the
out

object.

E.g.

<HTML>

<BODY>

<%



// This is a scriptlet.


Not
ice that the "date"



// variable we declare here is available in the



// embedded expression later on.



System.out.println( "Evaluating date now" );



java.util.Date date = new java.util.Date();

%>

Hello!


The time is now <%= date %>

</BODY>

</H
TML>


If we run the above example, we will notice the output from the "
System.out.println
" on
the server log.


This is a convenient way to do simple debugging. By itself a scriptlet does
not generate HTML.


If a scriptlet wants to generate HTML, it can use

a variable called
"
out
".


This variable does not need to be declared.


It is already predefined for scriptlets,
along with some other variables.


The following example shows how the scriptlet can
generate HTML output.


<HTML>

<BODY>

<%



// This script
let declares and initializes "date"



System.out.println (“Evaluating date now”);



java.util.Date date = new java.util.Date();

%>

Hello!


The time is now

<%



// This scriptlet generates HTML output



out.println (String.valueOf (date));

%>

</BOD
Y>

</HTML>

Directive elements

The directive elements specify information about the page itself that remains the same
between requests
--
for example, if session tracking is required or not, buffering
requirements, and the name of a page that should be used t
o report errors, if any.



JSP Directives

A JSP
directive

affects the overall structure of the servlet class. It usually has the
following form:


<%@

directive attribute="value"
%>


However, we can combine multiple attribute settings for a single directive
, as follows:


<%@

directive attribute1="value1"


attribute2="value2"


...


attributeN="valueN"
%>


The three main types of directives are:
page directive
,
include directive

and
tag lib
directive.


Element

Descripti
on

<%@ page ...
%>

Defines page
-
dependent attributes, such as session tracking, error page, and
buffering requirements

<%@ include ...
%>

Includes a file during the translation phase

<%@ taglib ...
%>

Declares a tag library, containing custom actions, t
hat is used in the page



The JSP
page

Directive

It is possible to use "
import
" statements in JSPs, but the syntax is a little different from
normal Java.


Try the following example:

<%@ page import="java.util.*" %>

<HTML>

<BODY>

<%



System.out.printl
n (“Evaluating date now”);



Date date = new Date ();

%>

Hello!


The time is now <%= date %>

</BODY> </HTML>


The first line in the above example is called a "directive".


A JSP "directive" starts with
<%@

characters. This one is a "page directive".


The

page directive can contain the list of
all imported packages.


To import more than one item, separate the package names by
commas.



E.g.: <%@ page import="java.util.*, java.text.*" %>


The
page

directive defines one or more of the following case
-
sensitiv
e attributes:



import="
package.class
"

or
import="
package.class1,...,package.classN
"
. This
specify what packages should be imported.

For example:
<%@ page import="java.util.*" %>

The
import

attribute is the only one that is allowed to appear multiple times
.



contentType="
MIME
-
Type
"

or
contentType="
MIME
-
Type
; charset=
Character
-
Set
”.

This specifies the MIME type of the output. The default is
text/html
.

For example, the directive

<%@ page contentType="text/plain" %>
has the same effect as the scriptlet

<% re
sponse.setContentType("text/plain"); %>




isThreadSafe="true|false"
. A value of
true

(the default) indicates normal servlet
processing, where multiple requests can be processed simultaneously with a
single servlet instance, under the assumption that the aut
hor synchronized access
to instance variables. A value of
false

indicates that the servlet should implement
SingleThreadModel
, with requests either delivered serially or with simultaneous
requests being given separate servlet instances.



session="true|fals
e"
. A value of
true

(the default) indicates that the predefined
variable
session

(of type
HttpSession
) should be bound to the existing session if
one exists, otherwise a new session should be created and bound to it. A value of
false

indicates that no sess
ions will be used, and attempts to access the variable
session

will result in errors at the time the JSP page is translated into a servlet.



buffer="
size
kb|none"
. This specifies the buffer size for the
JspWriter

out
. The
default is server
-
specific, but mus
t be at least
8kb
.



autoflush="true|false"
. A value of
true
, the default, indicates that the buffer should
be flushed when it is full. A value of
false
, rarely used, indicates that an exception
should be thrown when the buffer overflows. A value of
false

i
s illegal when also
using
buffer="none"
.



extends="
package.class
"
. This indicates the superclass of servlet that will be
generated. Use this with extreme caution, since th
e server may be using a custom
s
uperclass already.



info="
message
"
. This defines a st
ring that can be retrieved via the
getServletInfo

method.




errorPage="
url
"
. This specifies a JSP page that should process any
Throwable
s
thrown but not caught in the current page.



isErrorPage="true|false"
. This indicates whether or not the current page ca
n act as
the error page for another JSP page. The default is
false
.



language="java"
. At some point, this is intended to specify the underlying
language being used. For now, don't bother with this since
java

is both the default
and the only legal choice.

The XML syntax for defining directives is <jsp:directive.
directiveType

attribute=value />

For example, the XML equivalent of <%@ page import="java.util.*" %
> is

<jsp:directive.page import="java.util.*" />


The JSP
include

Directive

The include directive i
s used to physically include the contents of another file.


The
included file can be HTML or JSP or anything else
--

the result is as if the original JSP
file actually contained the included text.


To see this directive in action, create a new JSP

<HTML>

<BODY>

Going to include hello.jsp...<BR>

<%@ include file="hello.jsp" %>

</BODY>

</HTML>


This directive includes files at the time the JSP page is translated into a servlet. The
directive looks like this:



<%@ include file="relative url" %>


The URL spe
cified is normally interpreted relative to the JSP page that refers to it, but, as
with relative URLs in general, tell the system to interpret the URL relative to the home
directory of the Web server by starting the URL with a forward slash. The contents o
f the
included file are parsed as regular JSP text, and thus can include static HTML, scripting
elements, directives, and actions.

For example, many sites include a small navigation bar on each page. Due to problems
with HTML frames, this is usually imple
mented by way of a small table across the top of
the page or down the left
-
hand side, with the HTML repeated for each page in the site.
The
include

directive is a natural way of doing this, saving the developers from the
maintenance nightmare of actually c
opying the HTML into each separate file. Here's
some representative code:



<!DOCTYPE HTML PUBLIC "
-
//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE>Servlet Tutorial: JavaServer Pages (JSP) 1.0</TITLE>

<META NAME="author" CONTENT="webmaster@some
site.com">

<META NAME="keywords" CONTENT="...">

<META NAME="description" CONTENT="...">

<LINK REL=STYLESHEET


HREF="Site
-
Styles.css"


TYPE="text/css">

</HEAD>


<BODY>

<%@ include file="/navbar.html" %>

<!
--

Part specific to this page ...
--
>

</BO
DY>

</HTML>


Example Using Scripting Elements and Directives

Here is a simple example showing the use of JSP expressions, scriptlets, declarations, and
directives.

<! DOCTYPE HTML PUBLIC "
-
//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE>Using
Java Server Pages</TITLE>


<META NAME="author" CONTENT="Marty Hall
--

hall@apl.jhu.edu">

<META NAME="keywords"


CONTENT="JSP, JavaServer Pages,servlets">

<META NAME="description"


CONTENT="A quick example of the four main JSP tags.">

<LINK REL=ST
YLESHEET


HREF="My
-
Style
-
Sheet.css"


TYPE="text/css">

</HEAD>


<BODY BGCOLOR="#FDF5E6" TEXT="#000000" LINK="#0000EE"


VLINK="#551A8B" ALINK="#FF0000">


<CENTER>

<TABLE BORDER=5 BGCOLOR="#EF8429">


<TR><TH CLASS="TITLE">


Using JavaServ
er Pages</TABLE>

</CENTER><P>



Some dynamic content created using various JSP mechanisms:

<UL>


<LI><B>Expression.</B><BR>


Your hostname: <%= request.getRemoteHost() %>.


<LI><B>Scriptlet.</B><BR>


<% out.println("Attached GET data: " +



request.getQueryString()); %>


<LI><B>Declaration (plus expression).</B><BR>


<%! private int accessCount = 0; %>


Accesses to page since server reboot: <%= ++accessCount %>


<LI><B>Directive (plus expression).</B><BR>


<%@
page import = "java.util.*" %>


Current date: <%= new Date() %>

</UL>

</BODY>

</HTML>

Standard action elements

Action elements typically perform some action based on information that is required at
the exact time the JSP page is requested by a browser
. An action can, for instance, access
parameters sent with the request to do a database lookup. It can also dynamically
generate HTML, such as a table filled with information retrieved from an external
system.

The JSP specification defines a few standard a
ction elements, listed in the below table:

Action element

Description

<jsp:useBean>

Makes a JavaBeans component available in a page

<jsp:getProperty>

Gets a property value from a JavaBeans component and adds it to the
response

<jsp:setProperty>

Sets a J
avaBeans component property value

<jsp:include>

Includes the response from a servlet or JSP page during the request
processing phase

<jsp:forward>

Forwards the processing of a request to servlet or JSP page

<jsp:param>

Adds a parameter value to a reques
t handed off to another servlet or JSP
page using
<jsp:include>

or
<jsp:forward>

<jsp:plugin>

Generates HTML that contains the appropriate browser
-
dependent
elements (OBJECT or EMBED) needed to execute an applet with the
Java Plug
-
in software



The
jsp:us
eBean

Action


This action helps to load in a Java Bean to be used in the JSP page. This is a a very useful
capability because it lets to exploit the reusability of Java classes without sacrificing the
convenience that JSP adds over servlets alone. The simp
lest syntax for specifying that a
bean should be used is:


<jsp:useBean id="
name
" class="
package. class
" />


This usually means "instantiate an object of the class specified by
class
, and binds it to a
variable with the name specified by
id
." The differen
t attributes of useBean tag are:



Attributes

Usage

id

Gives a name to the variable that will reference the bean. A previous bean object
is used instead of instantiating a new one if one can be found with the same
id

and
scope

class

Designates the full p
ackage name of the bean.

scope

Indicates the context in which the bean should be made available. There are four
possible values:
page
,
request
,
session
, and
application
. The default,
page
,
indicates that the bean is only available on the current page (sto
red in the
PageContext

of the current page). A value of
request

indicates that the bean is
only available for the current client request (stored in the
ServletRequest

object).
A value of
session

indicates that the object is available to all pages during th
e
life of the current
HttpSession
. Finally, a value of
application

indicates that it is
available to all pages that share the same
ServletContext
.

type

Specifies the type of the variable that will refer to the object. This must match
the classname or be
a superclass or an interface that the class implements.
Remember that the
name

of the variable is designated via the
id

attribute.

beanName

Gives the name of the bean, as supply it to the
instantiate

method of
Beans
. It is permissible to supply a
type

and

a
beanName
, and omit the
class

attribute.



Then we can use
jsp:setProperty

and
jsp:getProperty

to modify and retrieve bean
properties.


The
jsp:setProperty

Action


jsp:setProperty


tag is used
to give values to properties of beans that have been referen
ced
earlier. We can do this in two contexts.

First, we can use
jsp:setProperty

after, but outside of, a
jsp:useBean

element, as below:




<jsp:useBean id="myName" ... />

...

<jsp:setProperty name="myName"


property="someProperty" ... />


In this case, the
jsp:setProperty

is executed regardless of whether a new bean was
instantiated or an existing bean was found.


A second context in which
jsp:setProperty

can appear is inside the body of a
jsp:useBean

element, as below:


<jsp:useBean id="m
yName" ... >


...


<jsp:setProperty name="myName"


property="someProperty" ... />

</jsp:useBean>

There are four possible attributes of
jsp:setProperty
:

Attribute

Usage

name

This required attribute designates the bean whose property w
ill be set.
The
jsp:useBean

element must appear before the
jsp:setProperty

element.


property

This required attribute indicates the property you want to set. However,
there is one special case: a value of
"*"

means that all request parameters
whose names
match bean property names will be passed to the
appropriate setter methods.


value

This optional attribute specifies the value for the property. String values
are automatically converted to numbers,
boolean
,
Boolean
,
byte
,
Byte
,
char
, and
Character

via th
e standard
valueOf

method in the target or
wrapper class.



param


This optional attribute designates the request parameter from which the
property should be derived. If the current request has no such parameter,
nothing is done: the system does
not

pass

null

to the setter method of the
property. Thus,
it

let the bean itself supply default values, overriding
them only when the request parameters say to do so.

E.g.

<jsp:setProperty name="orderBean"


property="numberOfItems"



param="numItems" />







We can modify its properties via
jsp:setProperty
, or by using a scriptlet and calling a
method explicitly on the object with the variable name specified earlier via the
id

attribute. Recall that with beans, when we say
"this bean has a property of type
X

called
foo
", we really mean "this class has a method called
getFoo

that returns something of

type
X
, and another method called
setFoo

that takes an
X

as an argument." We can supply
an explicit
value
, give a
param

attribu
te to say that the value is derived from the named
request parameter, or just list the property to indicate that the value should be derived
from the request parameter with the same name as the property. We read existing
properties in a JSP expression or s
criptlet by calling the appropriate
getXxx

method or
more commonly, by using the
jsp:getProperty

action.


The
jsp:getProperty

Action


This element retrieves the value of a bean property, converts it to a string, and inserts it
into the output. The two req
uired attributes are name, the name of a bean previously
referenced via jsp:useBean, and property, the property whose value should be inserted.
Here's an example



<jsp:useBean id="itemBean" ... />

...

<UL>


<LI>Number of items:


<jsp:getProperty na
me="itemBean" property="numItems" />


<LI>Cost of each:


<jsp:getProperty name="itemBean" property="unitCost" />

</UL>

Here is a very simple example that loads a bean and sets/gets a simple
String

parameter.

BeanTest.jsp


<!DOCTYPE HTML PUBLIC "
-
//W
3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE>Reusing JavaBeans in JSP</TITLE>

<LINK REL=STYLESHEET


HREF="My
-
Style
-
Sheet.css"


TYPE="text/css">

</HEAD>

<BODY>

<CENTER>

<TABLE BORDER=5>


<TR><TH CLASS="TITLE">


Reusing JavaBeans
in JSP</TABLE>

</CENTER>


<P>


<jsp:useBean id="test" class="hall.SimpleBean" />

<jsp:setProperty name="test"


property="message"


value="Hello WWW" />



<H1>Message: <I>

<jsp:getProperty name="test" property="m
essage" />

</I></H1>



</BODY>

</HTML>


SimpleBean.java

Here's the source code for the bean used in the BeanTest JSP page.


package hall;

public class SimpleBean {


private String message = "No message specified";



public String
getMessage
() {


return(message);


}



public void
setMessage
(String message) {


this.message = message;


}

}

Predefined Variables

To simplify code in JSP expressions and scriptlets, there are eight automatically defined
variables, sometimes called
implicit objec
ts
. The available variables are
request
,
response
,
out
,
session
,
application
,
config
,
pageContext
, and
page
. Details for each are
given below.


request

This is the
HttpServletRequest

associated with the request, and the request parameters
(via
getParamete
r
), the request type (
GET
,
POST
,
HEAD
, etc.), and the incoming HTTP
headers (cookies,
Referer
, etc.). Strictly speaking, request is allowed to be a subclass of
ServletRequest

other than
HttpServletRequest
, if the protocol in the request is something
other
than HTTP. This is almost never done in practice.


response

This is the
HttpServletResponse

associated with the response to the client. Note that,
since the output stream is buffered, it
is

legal to set HTTP status codes and response

headers, even though
this is not permitted in regular servlets once any output has been
sent to the client.


out

This is the
PrintWriter

used to send output to the client. However, in order to make the
response

object (see the previous section) useful, this is a buffered vers
ion of
PrintWriter

called
JspWriter
. We can adjust the buffer size, or even turn buffering off, through use of
the
buffer

attribute of the
page

directive. Also note that
out

is used almost exclusively in
scriptlets, since JSP expressions automatically get
placed in the output stream, and thus
rarely need to refer to
out

explicitly.


session

This is the
HttpSession

object associated with the request. Recall that sessions are created
automatically, so this variable is bound even if there was no incoming sess
ion reference.
The one exception is if use the
session

attribute of the
page

directive to turn sessions off,
in which case attempts to reference the session variable cause errors at the time the JSP
page is translated into a servlet.


application

This is

the
ServletContext

as obtained via
getServletConfig().getContext()
.


config

This is the
ServletConfig

object for this page.


pageContext

JSP introduced a new class called
PageContext

to encapsulate use of server
-
specific
features like higher performance

JspWriter
s. The idea is that,
if access

them through this
class rather than directly, the code will still run on "regular" servlet/JSP engines.


page

This is simply a synonym for
this
, and is not very useful in Java. It was created as a
placeholder for t
he time when the scripting language could be something other than Java.


Beans and Form processing


Forms are a very common method of interactions in web sites.


JSP makes forms
processing specially easy.

The standard way of handling forms in JSP is to
define a "bean".


This is not a full Java
bean.


We

just need to define a class that has a field corresponding to each field in the
form.


The class fields must have "setters" that match the names of the form fields.


For
instance,
consider

GetName.html

to

collect email address and age.

The new version of
GetName.html

is

<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>

W
hat's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>

<P><INPUT TYPE=SUBMIT>

</FORM>

</BODY>

</HTML>


To collect this data, we define a Java class with fields "
username
", "
email
" and "
age
" and
we provide setter methods "
setUsername
", "
setEmail
" and "
setAge
", a
s shown.


A
"setter" method is just a method that starts with "
set
" followed by the name of the field.


The first character of the field name is upper
-
cased.


So if the field is "
email
", its "
setter
"
method will be "
setEmail
".


Getter methods are defined s
imilarly, with "get" instead of
"set".


Note that the setters


(and getters) must be public.



public class UserData {



String username;



String email;



int age;




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; }




pub
lic int getAge() { return age; }

}


The method names must be exactly as shown.


Once
we
have defined the class, compile it
and make sure it is available in the web
-
server's classpath.


The server may also define
special folders where
we

can place bean clas
ses
.



Now let us change "
SaveName.jsp
" to use a bean to collect the data.

<jsp:useBean id="user" class="UserData" scope="session"/>

<jsp:setProperty name="user" property="*"/>


<HTML>

<BODY>

<A HREF="NextPage.jsp">Continue</A>

</BODY>

</HTML>


All we need

to do now is to add the
jsp:useBean

tag and the
jsp:setProperty

tag!


The
useBean tag will look for an instance of the "
UserData
" in the session.


If the instance is
already there, it will update the old instance.


Otherwise, it will create a new instance

of
UserData

(the instance of the
UserData

is called a bean), and put it in the session.

The setProperty tag will automatically collect the input data, match names against the
bean method names, and place the data in the bean!




NextPage.jsp

to retrieve
the data from bean..

<jsp:useBean id="user" class="UserData" scope="session"/>


<HTML>

<BODY>

You entered<BR>

Name: <%= user.getUsername() %><BR>

Email: <%= user.getEmail() %><BR>

Age: <%= user.getAge() %><BR>

</BODY>

</HTML>


Notice that the same useBean

tag is repeated.


The bean is available as the variable
named "
user
" of class "
UserData
".


The data entered by the user is all collected in the
bean.

Custom action elements and the JSP Standard Tag Library

JSTL

(JSP Standard Tag Library)

is a component t
echnology within the Java 2 Enterprise
Edition (J2EE) specification and is controlled by Sun Microsystems. JSTL is nothing
more than a set of simple and standard tag libraries that encapsulates the core
functionality commonly needed when writing dynamic JS
P pages. The JSTL tags are
organized into four libraries:



core
: Basic scripting functions such as loops, conditionals, and input/output;



xml
: XML processing;



fmt
: Internationalization and formatting of values such as currency and dates;



sql
: Database a
ccess.


There are several possible disadvantages to JSTL.



JSTL can add processing overhead to the server. Both Java scriptlet code and tag
libraries are compiled into a resulting servlet, which is then executed by the
servlet container. Java code embedded

in scriptlet tags is pretty much just copied
into the resulting servlet. JSTL tags, on the other hand, cause much more code to
be added to the servlet. In most cases this is not measurable, but it should be
considered.



Scriptlets are more powerful than J
STL tags. If you want to do everything in your
JSP pages, then you probably will want to stick with embedded Java code.
Although JSTL provides a powerful set of reusable libraries, it cannot do
everything that Java code can do. It is designed to facilitate

scripting the
presentation code that is typically found in the view tier of Model
-
View
-
Controller applications.

Example: JSTL cleaning up scriptlets.

In order to demonstrate the concept of cleaner, more maintainable JSP pages, let's look at
two versions
of a very simple JSP page. The first version uses traditional scriptlet tags
and the second version uses JSTL tags. Both pages implement the same logic. They grab
a List of AddressVO model objects from the request and then loop through the List,
printing o
ut each model's last name attribute if the last name is not null and not zero
-
length. Otherwise, it prints out "N/A". Finally, the page prints out a current timestamp.

With JSP scriptlet tags:


<%@ page import="com.ktaylor.model.AddressVO, java.util.*"
%>



<p><h1>Customer Names</h1></p>


<%


List addresses = (List)request.getAttribute("addresses");


Iterator addressIter = addresses.iterator();


while(addressIter.hasNext()) {


AddressVO address = (AddressVO)addressIter.next();


if((n
ull != address) &&


(null != address.getLastName()) &&


(address.getLastName().length() > 0)) {


%>


<%=address.getLastName()%><br/>


<%


}


else {


%>


N/A<br/>


<%


}



}


%>


<p><h5>Last Updated on: <%=n
ew Date()%></h5></p>

With JSTL tags:


<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>



<p><h1>Customer Names</h1></p>



<c:forEach items="${addresses}" var="address">


<c:choose>


<c:when test="${not empty address.lastName}"

>


<c:out value="${address.lastName}"/><br/>


</c:when>


<c:otherwise>


N/A<br/>


</c:otherwise>


</c:choose>


</c:forEach>



<jsp:useBean id="now" class="java.util.Date" />



<p><h5>Last Updated on: <c:out

value="${now}"/></h5></p>

JSTL

contains action elements for processes needed in most JSP applications, such as
conditional processing, database access, internationalization, and more.

Each tag
-
library will have its own tag
-
library specific documentation.


In order to use the
tag library, you use the "taglib" directive to specify where your tag library's "description"
resides.


For the Blazix tag library,


the (recommended) directive is as follows

<%@ taglib prefix="blx" uri="/blx.tld" %>


The "uri" speci
fies where to find the tag library description.


The "prefix" is unique for
the tag library.


This directive is saying that we will be using the tags in this library by
starting them with
blx:


The Blazix tag library provides a blx:getProperty tag.


This
tag can be used to allow the
user to edit form data.


In our GetName.jsp file, we will now add a jsp:useBean and place
the form inside blx:getProperty.

The new GetName.jsp is

<%@ taglib prefix="blx" uri="/blx.tld" %>

<jsp:useBean id="user" class="user.Us
erData" scope="session"/>


<HTML>

<BODY>

<blx:getProperty name="user" property="*">

<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>

W
hat's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>

<P><INPUT TYPE=SUBMIT>

</FORM>

</blx:getProperty>

</BODY>

</HTML>


Note that the blx:getProperty doesn't end with /> but is instead terminated by a separate
</blx:getProperty> line.


This puts all the form
input fields inside the blx:getProperty so
they can be appropriately modified by the tag library.

Try putting a link to GetName.jsp from the NextPage.jsp, and we will see that the bean's
data shows up automatically in the input fields.

The user can now e
dit the data.

We still have a couple of problems.


The user cannot clear out the name field.


Moreover,
if the user enters a bad item in the "age" field, something which is not a valid integer, a
Java exception occurs.

We will use another tag from the Bl
azix tag library to take care of this.


Blazix offers a
blx:setProperty tag that can be used to take care of these problems.


blx:setProperty

allows us to define an exception handler method.


If an exception occurs, we can collect
an error message for the
user and continue processing.

Following is a version of SaveName.jsp that processes any errors, and either shows the
user GetName.jsp again to user can enter the data correctly, or automatically forwards to
NextPage.jsp.

<%@ taglib prefix="blx" uri="/blx
.tld" %>

<%!



boolean haveError;



StringBuffer errors;




public void errorHandler( String field,



String value,



Exception ex )



{



haveError = true;



if ( errors == null )



errors = new StringBuffer();



else



errors.append( "<P>" );



errors.append( "<P>Value for field
\
"" +



field + "
\
" is invalid." );



if ( ex instanceof java.lang.NumberFormatException )





errors.append( " The value must be a number." );



}

%>

<%



// Variables must be initialized outside declaration!



haveError = false;



errors = null;

%>

<HTML>

<BODY>

<jsp:useBean id="user" class="user.UserData" scope="session"/>

<blx:setP
roperty name="user"



property="*"




onError="errorHandler"/>


<%



if ( haveError ) {



out.println( errors.toString());



pageContext.include( "GetName.jsp" );



} else



pageContext.forward( "NextPage.jsp" );

%>

</BODY>

</HT
ML>

Note that
haveError

and
errors

must be re
-
initialized each time, therefore they are
being initialized outside of the declaration.

Here, if an error occurs during the processing of
blx:setProperty
, we display the error
and then include the
GetName.jsp

again so user can correct the error.


If no errors occur,
we automatically forward the user to
NextPage.jsp
.

There is still a problem with the forms, the "age" shows up as zero initially rather than
being empty.


This can be fixed by adding "
emptyInt=0"

t
o both the
blx:getProperty

and
blx:setProperty

tags (bean fields should be initialized to 0.)


It happens that "0" is
not a valid value for age, so we can use "0" to mark empty strings.


If "0" were a valid
value for age, we could have added "
emptyInt=
-
1
"

(and made sure to initialize the bean
fields to
-
1.)

Another small problem is that the "<HTML>" tag gets doubled if there is an error and we
end up including "GetName.jsp".


A more elegant solution is to remove the out.println,
and pass back the error as

shown

<%



if ( haveError ) {



request.setAttribute( "errors",



errors.toString());



pageContext.forward( "GetName.jsp" );



} else



pageContext.forward( "NextPage.jsp" );

%>

We can then do a "
request.getAttribute
" in the
GetName.jsp
, and if the returned
value is non
-
null, display the error.