Java Server Pages Tutorial

mobdescriptiveΛογισμικό & κατασκευή λογ/κού

28 Οκτ 2013 (πριν από 3 χρόνια και 5 μήνες)

84 εμφανίσεις

Java Server Pages


What is JSP?

JSP, or Java Server Pages, is technology invented by Sun Microsystems which
allows the easy creation and maintenance of server side HTML pages, which can be used

both a kind of Dynamic HTML and CGI replacement. Conceptually, JSP pages are
similar to ASP pages, Cold Fusion Markup Pages, and perl scripts

Why JSP?

JavaServer Pages technology help you to write dynamic Web pages as easily and
simply as possible, wit
h maximum power and flexibility. The need for JSP are:

Allows you to write once, run anywhere. The JavaServer Pages technology is
entirely platform
independent, both in its dynamic Web pages and its
underlying server components. You can write the dynamic
Web pages on any
platform, run them on any Web server, and access them from any Web
browser. You can also build and run the server components, which are
JavaBeans or Java Servlets, on any server platform.

Emphasizes components. JavaServer Pages emphasize
s the use of reusable,
platform server components Written in Java. This saves you
considerable development time while giving you the power and flexibility of
JavaBeans and Java Servlets. And because components do much of the
processing work, componen
t development is more cleanly separated from
Web design, improving the productivity of cross
functional teams.

Makes dynamic Web sites easy to build. JavaServer Pages are HTML files
written in a combination of industry
standard HTML, JavaServer Pages HTML

tags, and

if you like

Java as a scripting language. A JavaServer Pages
file has the extension

and calls reusable components that reside on the
server. It's as simple as that.

For one thing, JSP/Servlets are much higher performance than their
counterparts, due to the inprocess nature of the execution and memory
sharing between scripts.

JSP/Servlets allow the user to create their own utility, or business logic
classes using Java and call them easily from within their JSP/HTML pages

ly, the components are JavaBeans or Java Servlets.

Requirements to run JSP pages?

You need what is known as a "Servlet Engine", which attaches to your web

You also need a Java SDK, which you should install on your Server

installing the
Servlet Engine.

to run JSP pages, you MUST have
the Java SDK NOT just the JRE.)

JSP pages require the compiler to be present on the Server, therefore you
MUST install the SDK. In contrast, Servlets do not require the compiler to be
present on the


Finally, the Servlet Engine must support JSP, preferably v 1.0 or higher. The
most popular servlet engines right now seem to be JRUN & ServletExec.

JSP compared to ASP

JSP allows the inclusion of Java coded commands into a web page plus the use o
Java Beans. Java Beans are compiled Java components. This implies that the Java
Servlets plus JSP combination give the full power of a programming language, and a
fully object
oriented one at that, in the creation of web pages. ASP uses VBScript
which is

at its best a simplistic scripting language. VBScript is a very small subset of
Visual Basic. Also Visual Basic is not an object
oriented programming language.

Java is platform and browser independent. VBScript is not. In fact VBScript will
generally not
function very well with Netscape or any other browser other than the
Internet Explorer, for instance, America On
Line. Also since Java is platform
independant JSP pages can be run on any machine regardless of operating system
without recompilation

ver Pages Access Model

You can apply the JavaServer Pages technology in two ways:

A client makes a request that is sent to a JavaServer Pages (
) file. The

file accesses server components that generate dynamic content and displays the
dynamic cont
ent in the browser.

A user makes a request that is sent to a Java Servlet that generates a result and
stores the result in component. The servlet then calls a JavaServer Pages file,
which accesses the component and displays the dynamic content in the brow

Method 1: A request sent to a JavaServer Pages file










Method 2: A request sent to a Java Servlet

In Method 1 or Method 2, the JavaServer Pages file is identified to the server by


this tells the server t
hat special handling is required. The first time a
request is made for such a file

either directly from a client browser or from a servlet


file is compiled into an object. (For that reason, there can be a slight delay on
the first request fo
r a

page.) The output from the object is standard HTML, which
the browser interprets and displays as usual.

Scripting of Java Server Pages

The scripting of JSP’s can be categorized into

Component tags which are very similar to HTML tags and used a
long with HTML tags

Scripting tags which allows the user to insert customized scripting code into the .JSP

Component tags

These tags are simple to use and are very much like HTML, tag and attribute
names are case

Their similarity to HTML ta
gs in both look and feel makes these component
centric tags easy to distinguish from the infrequently used scripting
centric tags. They
follow a hierarchical naming structure.

A hierarchical name is constructed as follows:


An exam
ple would be:


where the personBean is a Bean containing a property called name.









The use of colons (:) rather than periods (.) also helps distinguish this naming
convention from Java syntax.

Some of the main Component Tags:

JavaServer P
ages Beans


The syntax to refer to a Bean inside a .jsp file is defined by the USEBEAN tag. Any non
implicit Bean must first be declared this way before it and its properties can be accessed later in
the .jsp file.




LIFESPAN="page|session|application" >



The SETONCREATE tag defines a value for a property which will automatically be set
once for each Bean (through JavaBean
s introspection) when the Bean is created. The property
value can be a string, integer, or float.


" >


<USEBEAN Name=”test”

TYPE = “test.class”


EANPROPERTY="testProperty" VALUE="1">


A SETONCREATE tag can appear only between the opening <USEBEAN ...> and
closing </USEBEAN> tags. More than one SETONCREATE tag may appear in that position.
SETONCREATE tags are not valid anywhere else in
the file.

When the SETFROMREQUEST tag is present, all request parameters (query or form
based) are examined. The appropriate property setter methods from the Bean's

called for each property depending on the attribute specified.



Note that this general syntax results in the following 3 cases:


" >

When the

is used, BEANPROPERTY matches any property name.
In t
his case, all request parameters are copied into the Bean, matching parameter names
in the request to property names in the Bean

the PARAMNAME attribute, if present, is


" >

When a specific BEANPROPERT
Y value is provided but a PARAMNAME value is not,
the PARAMNAME value is assumed to be equivalent to the BEANPROPERTY value.

For example


would be read as if it said:




This is the fully qualified case. In this form, the tag says to copy into the Bean property
, the value of the request parameter named










The tagging indicates two possible values for the foobar Bean's fooba

"Salaried" and the value of the employmentStatus parameter. It obviously cannot hold both
values simultaenously so how is the conflict resolved?

As noted earlier, SETFROMREQUEST and SETONCREATE tags can only appear
between the opening <USEBEA
N ...> and closing </USEBEAN> tags. Within a given USEBEAN
pair of tags, all SETONCREATE tags are processed first (in their order of appearance) and then
all SETFROMREQUEST tags are processed (in their order of appearance). Therefore, in the
case above, th
e value of the BEANPROPERTY foobarProperty would first be assigned "Salaried"
and then be assigned the value associated with the request parameter employmentStatus.

property display tags

<DISPLAY ... > shows a specific, single
valued Bean proper

<LOOP... > </LOOP> provide a repeat mechanism around the request to display a specific Bean
property value, <DISPLAY ... > , in the case where the "value" is actually a list of values.

JavaServer Pages conditions:

Syntax that allows the inclusion
or exclusion of a block of code, based on whether the
specified Bean property matches the requested value

that is, whether the condition is true that
the property value matches the requested value.

If the INCLUDEIF tag is used and the condition evaluat
es to true, the code contained
between the start and end tags is included in the processing of the page; otherwise it is

Likewise, if the EXCLUDEIF tag is used and the condition evaluates to true, the code
between the start and end tags is excluded i
n the processing of the page, otherwise it is

INCLUDEIF and EXCLUDEIF tags can only be used with Bean properties that return either a
String type or a Java native type. If a Bean property used in these tag returns a Java native type,
that returned va
lue is automatically converted to a String type.

The syntax for the INCLUDEIF tags is as follows:

]+" VALUE="



Similarly, the syntax for the EXCLUDEIF tags is as follows:

]+" VALUE="


JavaServer Pages implicit Beans

The fol
lowing Beans are automatically available for use within a JavaServer Pages file

do not require USEBEAN tags prior to their use:


containing information from the incoming client request.



containing information about the last er
ror accessing a given .jsp file.

The exception Bean contains information about the most recent error in accessing the
page in which the ERRORPAGE directive appears. The ERRORPAGE directive names the
file to be displayed should an error condition be encou
ntered. The information in the
exception Bean is only accessible from the page designated by the ERRORPAGE directive.

The request Bean contains information from the client request. (This Bean is not valid for
use within the SCRIPT, scriptlet <%... %>, or
expression <%= ... %> tags.)

Additional details on the nature and use of these implicit Beans are provided below.

exception Bean

Errors may occur either at compile time, when the .jsp file is first compiled to an object
(see the Access Model section for
information on this) or at runtime when the compiled object is
actually used. An example of a compile time error is a .jsp file with a syntax error, which may be
as simple as a misspelled or missing required attribute. An example of a runtime time error is

.jsp file that references an invalid class file for the creation of a new Bean.

The exception Bean is of type java.lang.Throwable. Although all of the methods of that
class are available, JavaServer Pages authors will typically use the getMessage method
, and
component or application developers the printStack Trace method. The API for

is provided in the appendix of this document.

request Bean

Information from the incoming client request is automatically made available through the
est Bean. The request Bean provides access to CGI
like environment variables, request
parameters, and request headers.

The request Bean properties can be accessed in the DISPLAY, LOOP

Briefly, the listing of av
ailable request Bean properties is:


















In addition to the above

properties, the request Bean has two nested Beans. The properties of
these nested Beans, and the value assigned to their properties, are determined dynamically. The
request Bean's nested Beans are:


The nested headers Bean contains information fr
om the HTTP request header. For each
header defined by the HTTP protocol, there is a property of the same name. For
example, here's how you might display the HTTP header "user

<DISPLAY PROPERTY="request:headers:user
agent" >


The nested pa
rams Bean contains user
provided request parameters (such as form or
query based parameters). As an example, consider a form with name and address fields.
On submission by the user, the action may be posted as:

If you then wanted to show those request parameters in your response to the user
(client), you could do so with the following syntax:

<DISPLAY PROPERTY="request:params:name" >

Scripting Tags

JavaServer Pages directives:

Syntax that in
structs the JavaServer Pages

(JavaServer Pages
mechanism) on the settings to be used for a given .jsp file. (The syntax is extensible to allow
other tags in the future.) Directives are denoted by the <%@ ...%> tag.

When directives are prese
nt in a JavaServer Pages file, they should appear at the top.
The general syntax of the JavaServer Pages directive is:

" %>

Note that a space is required between the <%@ and the

parts of the tag.

The possible values the variab
le can take are


: specifies the language used for scripting

Eg: <%@ language="java" %>



The import variable defines the list of packages that will be imported for use
within the compiled
page object. This is a comma
separated list of lang
package names or class names that the compiled
page object imports.

<%@ import="*,java.util.Hashtable" %>


: The errorpage variable defines the .jsp or .html file to be returned to
the client if the current .jsp page re
sults in an error

Eg: <%@ errorpage="contactwebmaster.html" %>

JavaServer Pages declarations:

All declarations that define page
wide variables for the compiled page file, and all
methods that are class
wide definitions, can be defined in a JavaServer
Pages file within the
SCRIPT tag pair.

The general form of a JavaServer Pages declaration is:





int i = 0; String foo = "Hello";

private void foo() {

// some code



Note : I
f RUNAT is not specified, it defaults to "client" and the statements enclosed by the
SCRIPT tags will be passed unprocessed in the page sent to the client

JavaServer Pages scriptlets:

Syntax that defines scripting language code to be executed. Scriptl
ets are denoted by the
<% ... %> tag.

Scriptlets can enclose any code that is valid for the language specified in the

The general form of a JavaServer Pages scriptlet is:

<% ... %>

Note that a space is required between the <% and th
e remainder of the tag.

The script specified can rely upon a set of predefined variables: servletrequest,
servletresponse, in, and out.

An example of the scriptlet tags appears below:

<% out.println("Hello"); %>

Another example:


foo = request.get



JavaServer Pages expressions:

Syntax that defines an expression that will be evaluated. The value of the expression will
be substituted where the expression occurs. Expressions are denoted by the <%= ... %>

You can think of an expression as a description of, or placeholder for, an item you want
evaluated. The expression is evaluated and then it is replaced by its value. The value is
always converted to a string. Conversions to string representation are provi
automatically for all primitive types (such as


The general form of a JavaServer Pages expression is:



Note that a space is required between the <% and the

parts of the tag.

<p>I live at: <%= myaddress %>

Where myaddress is a variable

Implicit Variables

: the request class as defined by
javax.servlet.http.HttpServlet Request

: the response class as defined by

: the output writer class as defin
ed by
. That is, output to the client

: the servlet input reader class as defined by
. That is, input from
the client browser.

Note: These predefined variables cannot be used within <SCRIPT> </SCRIPT> d
eclaration tags

Session Tracking

The Hypertext Transport Protocol (HTTP), on which the Web is built, is
. That
means that each HTTP transaction opens with the client's request to the server for a
resource (typically a webpage) and closes with the

server's response. The next request
initiated by that client carries no information, or
, from the last request. In many
situations, that lack of ability to store information from one request to another quickly
becomes a burden for both the client an
d the service provider.

The following scenarios are typical situations where the ability to store information from
one request to another is desirable:

shopping scenarios

Without session tracking, you would have no way to store the information about

your selected items (no "shopping cart"). You'd have to select and buy each item
in a series of individual transactions.

access scenarios.

Without session tracking, you would have to provide your identification and
password at not just the fir
st entry page to a restricted area of a website
(perhaps restricted by membership level), but for every page you accessed in
that area of the website.

Session tracking is a high
level replacement for the traditional cookie setting and
management with which

you may already be familiar. The JSP session tracking feature
tracks client
serverinteractions via objects rather than strings.

With JavaServer Pages, webpage authors don't need to worry about managing cookies

the server takes care of the saving state

between the client and server. Because
JavaServer Pages takes care of thread contention, you can be assured there is only one
thread working on your session object

similarly for applications. Request objects are
strictly thread

(The characteristi
cs of session tracking

how many objects can be in a given session,
how long a session lasts, and a number of other session characteristics

configurable by the server administrator.)

In the sample code below, the .jsp file contains a Bean. When th
e .jsp file is requested
by a client, the Bean component and an associated session object are created (if not
currently in existence) or located (if they already exist). Once identified, information can
be stored into or retrieved from the session object.
In this example, if information about
selected items had been stored into the session object on previous pages (requests),
that information would be retrieved and displayed on this page.



<USEBEAN NAME="cart" TYPE=sessions.DummyCart



You have the following items in your cart: <ol>


<li> <DISPLAY PROPERTY=x> </li>





Various scope of objects

Objects or variable
s can be considered of having different levels of scope
within the application. The different scopes provided by JSP are





: Applications can be thought of as a set of cooperating resources
(servlets, applets, image file
, or webpages) that share information between them to
achieve some end functionality. The information is stored in a shared data
object, which
is accessible by any of the resources that belong to the application. An application
resource can put information

into the shared data
object or retrieve information from
that data object

For example, a Web designer might want to add a counter to a

page to show how many times the page has been accessed. The

might call a Bean named
, display t
he value of the Bean's

property, and set the values of the Bean's




<USEBEAN NAME="cbean" TYPE = "counter.Counter" LIFESPAN =




This page has been accessed <DISPLAY PROPERTY="cbean:counter"> times.



: This means that the objects lifetime is the there until the the user session is

with the server. Objects having session lifetime can be accessed across requests
by the same user. It ends only when there is a session time out or the user closes the


<USEBEAN NAME="cpageno" TYPE = "page.Pageno" LIFESPAN = "session">




Page number <DISPLAY PROPERTY="page.Pageno">


: This means that the objects lifetime limited to a partic
ular page. Once the user
navigates away from the page, its value is lost.



<USEBEAN NAME=bar TYPE=jsp.beans.LunchSpecial LIFESPAN=page >


meringue pie">


<h1>Welcome to Jake's Emporium!</h1>

<h2>Today's Lunch Special is:</h2>



<li>Hot and tasty <DISPLAY PROPERTY="bar:soup" PLACEHOLDER="tomato">

<li>Hearty <DISPLAY PROPERTY="bar:sandwich" PLACEHOLDER="cheese" >

<li>Homemade <DISPLAY PROPERTY="bar:dessert" PLACEHOLDER="apple"





To invoke a .jsp file

To issue a client request for a .jsp file on a webserver which supports JavaServer Pages,
you would enter an URL of the f
ollowing format into the locator field of your browser:


For example:


A few samples:


The date JSP


<jsp:USEBEAN id="clock" type="calendar.JspCalendar" scope="page">



li>Day of month: is <DISPLAY property=clock:dayOfMonth


Day of month: is <jsp:getProperty property="clock:dayOfMonth"/>


Year: is <DISPLAY property=clock:year>


Month: is <DISPLAY property=clock:month>



is <DISPLAY property=clock:time>


Date: is <DISPLAY property=clock:date>


Day: is <DISPLAY property=clock:day>


Day Of Year: is <DISPLAY property=clock:dayOfYear>


Week Of Year: is <DISPLAY property=clock:weekOfYear>


era: is <DI
SPLAY property=clock:era>


DST Offset: is <DISPLAY property=clock:dSTOffset>


Zone Offset: is <DISPLAY property=clock:zoneOffset>


Timezone: is <DISPLAY property=clock:uSTimeZone>

</ul> </html>

The source for Bean:



import java.text.DateFormat;

import java.util.*;

public class JspCalendar {

Calendar calendar = null;

public JspCalendar() {

calendar = Calendar.getInstance();

Date trialTime = new Date();



blic int getYear() {

return calendar.get(Calendar.YEAR);


public String getMonth() {

int m = getMonthInt();

String[] months = new String [] { "January", "February", "March",

"April", "May", "June",

"July", "August", "September",

"October", "November", "December" };

if (m > 12)

return "Unknown to Man";

return months[m



public String getDay() {

int x = getDayOfWeek();

String[] days = new String[] {"Sunday", "Monday", "Tuesday", "Wednesday",

"Thursday", "Friday", "Saturday"};

if (x > 7)

return "Unknown to Man";

return days[x



public int getMonthInt() {

return 1 + calendar.get(Calendar.MONTH);


public String getDate() {

return getMonthInt() + "/" + ge
tDayOfMonth() + "/" + getYear();


public String getTime() {

return getHour() + ":" + getMinute() + ":" + getSecond();


public int getDayOfMonth() {

return calendar.get(Calendar.DAY_OF_MONTH);


public int getDayOfYear() {

return calendar.get(Calendar.DAY_OF_YEAR);


public int getWeekOfYear() {

return calendar.get(Calendar.WEEK_OF_YEAR);


public int getWeekOfMonth() {

return calendar.get(Calendar.WEEK_OF_MONTH);


public int getDayOfWeek() {

eturn calendar.get(Calendar.DAY_OF_WEEK);


public int getHour() {

return calendar.get(Calendar.HOUR_OF_DAY);


public int getMinute() {

return calendar.get(Calendar.MINUTE);


public int getSecond() {

return calendar


public static void main(String args[]) throws


JspCalendar db = new JspCalendar();

p("date: " + db.getDayOfMonth());

p("year: " + db.getYear());

p("month: " + db.getMonth());

p("time: " + db.

p("date: " + db.getDate());

p("Day: " + db.getDay());

p("DayOfYear: " + db.getDayOfYear());

p("WeekOfYear: " + db.getWeekOfYear());

p("era: " + db.getEra());

p("ampm: " + db.getAMPM());

p("DST: " + db.getDSTOffset());

p("ZONE Offset: "
+ db.getZoneOffset());

p("TIMEZONE: " + db.getUSTimeZone());;


private static void p(String x)




public int getEra()


return calendar.get(Calendar.ERA);


String getUSTimeZone()


String[] zones = new String[] {"Hawaii", "Alaskan", "Pacific",

"Mountain", "Central", "Eastern"};

return zones[10 + getZoneOffset()];


public int getZoneOffset()


return calendar.get(Calendar.ZO


public int getDSTOffset()


return calendar.get(Calendar.DST_OFFSET)/(60*60*1000);


public int getAMPM()


return calendar.get(Calendar.AM_PM);





Your browser is <
DISPLAY property=request:headers:user


<EXCLUDEIF property=request:headers:user

value = MSIE

match = contains>

<h1> We have detected a Netscape Navigator Browser</h1>


<INCLUDEIF property=request:headers:user

value = MSIE

match = contains>

<h1> We have detected a Internet Explorer Browser</h1>



Scripting Syntax

HTML Comment

Generates a comment that is sent to the client.

JSP Syntax


comment [ <%= expression %> ]



This file displays the homepage

Displays in the page source:


This file displays the homepage

A hidden comment marks text or lines that the JSP container should ignore. A
hidden comment is useful when you want to hide or “comment out”

part of your JSP
page. The JSP container does not process anything within the <%

characters. A hidden comment is not sent to the client, either in the displayed JSP page
or the page source.

You can use any characters in the body of the comment
except the closing
combination. If you need to use
%> in your comment, you can escape it by typing


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

JSP Syntax

<%! declaration; [ declaration; ]+

... %>


<%! int i = 0; %>

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

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

When you write a d
eclaration in a JSP file, remember these rules:

You must end the declaration with a semicolon (the same rule as for a Scriptlet, but
the opposite of an Expression).

You can already use variables or methods that are declared in packages imported by
the <%@

page %> directive, without declaring them in a declaration element.


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

JSP Syntax

<%= expression %>


The map file has <font color="blue">
<%= map.size() %>
</font> en

Good guess, but nope. Try <b>
<%= numguess.getHint() %>

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 to a String, you can use an
expression within a line of text, whether or not it is tagged with HTML, in a JSP file.


Contains a code fragment valid in the page scripting language.

JSP Syntax

<% code fragment %>



tring name = null;

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


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, you can do any
of the following:

Declare variables or methods to use later in the file (see also Declaration).

Write expressions valid in the page scripting language (see also Expression).

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

Write any other statement valid in the scripting language used in the JSP page (if
you use the Java programming language, the statements must conform to the Java
Language Specification).

Any text, HTML tags, or JSP elements you write must be outside th
e 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.

Include Directive

Includes a static file in a JSP file, parsing the file
’s JSP elements.

JSP Syntax

<%@ include file="relativeURL" %>




<head><title>An Include Test</title></head>

<body bgcolor="white">

<font color="blue">

The current date and time are

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





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

<%= (new java.util.Date() ).toLocaleString() %>

Displays in the page:

The current date and time are

Aug 30, 1999 2:38:40

The <%@ include %> directive inserts a file of text or code in a JSP file at
on time, when the JSP file is compiled. When you use the <%@ include %>
directive, the include process is static. A static include means that the text of the
included file is added to the JSP file. The included file can be a JSP file, HTML file, or
text fi
le. If the included file is a JSP file, its JSP elements are parsed and their results
included (along with any other text) in the JSP file.

The included file can be an HTML file, a JSP file, a text file, or a code file written
in the Java programming langu
age. Be careful, though, that the included file does not
contain <html>, </html>, <body>,or</body> tags. Because the entire content of the
included file is added at that location in the JSP file, these tags would conflict with the
same tags in the calling
JSP file, causing an error.

Page Directive

Defines attributes that apply to an entire JSP page.

JSP Syntax

<%@ page

[ language="
" ]

[ extends="package .class" ]

[ import= "{package .class | package.*}, ..." ]

[ session="
|false" ]

[ buffer="none|
|sizekb" ]

[ autoFlush="
|false" ]

[ isThreadSafe="
|false" ]

[ info="text" ]

[ errorPage="relativeURL" ]

[ contentType="mimeType [ ;charset=characterSet ]" |

"text/html ; charset=ISO

[ isErrorPage="true|
" ]



<%@ page import="ja
va.util.*, java.lang.*" %>

<%@ page buffer="5kb" autoFlush="false" %>

<%@ page errorPage="error.jsp" %>

The <%@ page %> directive applies to an entire JSP file and any of its static
include files, which together are called a translation unit. A static inc
lude file is a file
whose content becomes part of the calling JSP file. The <%@ page %> directive does
not apply to any dynamic include files; see <jsp:include> for more information.

You can use the <%@ page %> directive more than once in a translation uni
but you can only use each attribute, except import, once. Because the import attribute is
similar to the import statement in the Java programming language, you can use a <%@
page %> directive with import more than once in a JSP file or translation unit.



The scripting language used in scriptlets, declarations, and expressions in the JSP file
and any included files. In this release, the only allowed value is java.


The fully qualified name of the superclass

of the Java class file this JSP file will be
compiled to. Use this attribute cautiously, as it can limit the JSP container’s ability to
provide a specialized superclass that improves the quality of the compiled file.

import="{ package.class | package.* },


A comma
separated list of Java packages that the JSP file should import. The packages
(and their classes) are available to scriptlets, expressions, and declarations within the
JSP file. If you want to import more than one package, you can specify a c
separated list after import or you can use import more than once in a JSP file.

The following packages are implicitly imported, so you don’t need to specify

them with the import attribute:





You must place the import attribute before the element that calls the imported class.


Whether the client must join an HTTP session in order to use the JSP page. If the value
is true, the session object refers to the current or n
ew session. If the value is false, you
cannot use the session object or a <jsp:useBean> element with scope=session in the
JSP file. Either of these usages would cause a translation
time error. The default value is


The buffer
size in kilobytes used by the out object to handle output sent from the
compiled JSP page to the client Web browser. The default value is 8kb.If you specify a
buffer size, the output is buffered with at least the size you specified.


Whether the buffered output should be flushed automatically when the buffer is full. If
set to true (the default value), the buffer will be flushed. If set to false, an exception will
be raised when the buffer overflows. You cannot set autoFlush to false w
hen buffer is
set to none.


Whether thread safety is implemented in the JSP file. The default value is true, which
means that the JSP container can send multiple, concurrent client requests to the JSP
page. You must write code in t
he JSP page to synchronize the multiple client threads. If
you use false, the JSP container sends client requests one at a time to the JSP page.


A text string that is incorporated verbatim into the compiled JSP page. You can later
retrieve the
string with the Servlet.getServletInfo() method.


A pathname to a JSP file that this JSP file sends exceptions to. If the pathname begins
with a /, the path is relative to the JSP application’s document root directory and is

by the Web server. If not, the pathname is relative to the current JSP file.


Whether the JSP file displays an error page. If set to true, you can use the exception
object in the JSP file. If set to false (the default value), you c
annot use the exception
object in the JSP file.

contentType="mimeType [;charset=characterSet ]" |


The MIME type and character encoding the JSP file uses for the response it sends to the
client. You can use any MIME type or ch
aracter set that are valid for the JSP container.
The default MIME type is text/html, and the default character set is ISO

Taglib Directive

Defines a tag library and prefix for the custom tags used in the JSP page.

JSP Syntax

<%@ taglib uri
="URIToTagLibrary" prefix="tagPrefix" %>


<%@ taglib uri="" prefix="public" %>





The <%@ taglib %> directive declares that the JSP file uses custom tags,
names the tag library that defines t
hem, and specifies their tag prefix. Here, the term
custom tag refers to both tags and elements. Because JSP files can be converted to
XML, it is important to understand the relationship of tags and elements. A tag is simply
a short piece of markup that is

part of a JSP element. A JSP element is a unit of JSP
syntax that has an XML equivalent with a start tag and an end tag. An element can also
contain other text, tags, or elements. For example, a jsp:plugin element always has a
<jsp:plugin> start tag and a

</jsp:plugin> end tag and may have a <jsp:params>
element and a <jsp:fallback> element. You must use a <%@ taglib %> directive before
you use the custom tag in a JSP file.

You can use more than one <%@ taglib %> directive in a JSP file, but the prefix
ined in each must be unique.



The Uniform Resource Identifier (URI) that uniquely names the set of custom tags
associated with the named tag prefix.


The prefix that precedes the custom tag name, for exam
ple, public in <public:loop>.
Empty prefixes are illegal. If you are developing or using custom tags, you cannot use
the tag prefixes jsp, jspx, java, javax, servlet, sun, and sunw, as they are reserved by
Sun Microsystems.


Forwards a client

request to an HTML file, JSP file, or servlet for processing.

JSP Syntax

<jsp:forward page="{relativeURL | <%= expression %>}" />


<jsp:forward page="{relativeURL | <%= expression %>}" >

<jsp:param name="parameterName"

value={"parameterValue" | <%= exp
ression %>} />+



<jsp:forward page="/servlet/login" />

<jsp:forward page="/servlet/login">

<jsp:param name="username" value="jsmith" />


The <jsp:forward> element forwards the request object containing the client
request i
nformation from one JSP file to another file. The target file can be an HTML file,
another JSP file, or a servlet, as long as it is in the same application context as the
forwarding JSP file. The lines in the source JSP file after the <jsp:forward> element

not processed. You can pass parameter names and values to the target file by using a
<jsp:param> clause. An example of this would be passing the parameter name
username (with

name="username") and the value scott (with value="scott") to a servlet login

file as
part of the request. If you use <jsp:param>, the target file should be a dynamic file that
can handle the parameters.


page="{relativeURL | <%= expression %>}"

A String or an expression representing the relative URL of the file to which
you are
forwarding the request. The file can be another JSP file, a servlet, or any other dynamic
file that can handle a request object.

The relative URL looks like a path

it cannot contain a protocol name, port number, or
domain name. The URL can be absol
ute or relative to the current JSP file. If it is
absolute (beginning with a /), the path is resolved by your Web or application server.

<jsp:param name="parameterName" value={"parameterValue" | <%= expression
%>} />+

Sends one or more name/value pairs as
parameters to a dynamic file. The target file
should be dynamic, that is, a JSP file, servlet, or other file that can process the data that
is sent to it as parameters.


Gets the value of a Bean property so that you can display it in a r
esult page.

JSP Syntax

<jsp:getProperty name="beanInstanceName" property="propertyName" />


<jsp:useBean id="calendar" scope="page" class="employee.Calendar" />


Calendar of
<jsp:getProperty name="calendar" property="username" />


The <jsp:g
etProperty> element gets a Bean property value using the property’s
getter methods and displays the property value in a JSP page. You must create or locate
a Bean with <jsp:useBean> before you use <jsp:getProperty>. The <jsp:getProperty>
element has a few
limitations you should be aware of:

You cannot use <jsp:getProperty> to retrieve the values of an indexed property.

You can use <jsp:getProperty> with JavaBeans components, but not with enterprise
beans. As alternatives, you can write a JSP page that ret
rieves values from a Bean
that in turn retrieves values from an enterprise bean, or you can write a custom tag
that retrieves values from an enterprise bean directly.



The name of an object (usually an instance of a Bean)

as declared in a <jsp:useBean>


The name of the Bean property whose value you want to display. The property is
declared as a variable in a Bean and must have a corresponding getter method.


Includes either a s
tatic or dynamic file in a JSP file.

JSP Syntax

<jsp:include page="{relativeURL | <%= expression %>}" flush="true" />


<jsp:include page="{relativeURL | <%= expression %>}" flush="true" >

<jsp:param name="parameterName"

value={ "parameterValue" | <%= exp
ression %> } />+



<jsp:include page="scripts/login.jsp" />

<jsp:include page="copyright.html" />

<jsp:include page="/index.html" />

<jsp:include page="scripts/login.jsp">

<jsp:param name="username" value="jsmith" />


The <j
sp:include> element allows you to include either a static or dynamic file in
a JSP file. The results of including static and dynamic files are quite different. If the file
is static, its content is included in the calling JSP file. If the file is dynamic,
it acts on a
request and sends back a result that is included in the JSP page. When the include
action is finished, the JSP container continues processing the remainder of the JSP file.

You cannot always determine from a pathname if a file is static or dyn
amic. For
example, http://server:8080/index.html might map to a dynamic servlet through a Web
server alias. The <jsp:include> element handles both types of files, so it is convenient
to use when you don’t know whether the file is static or dynamic. If the
included file is
dynamic, you can use a <jsp:param> clause to pass the name and value of a parameter
to the dynamic file. As an example, you could pass the string username and a user’s
name to a login form that is coded in a JSP file.


elativeURL | <%= expression %>}"

The relative URL that locates the file to be included, or an expression that evaluates
to a String equivalent to the relative URL. The relative URL looks like a pathname

cannot contain a protocol name, port

number, or do
main name. The URL can be absolute or relative to the current JSP file. If
it is absolute (beginning with a /), the pathname is resolved by your Web or application


You must include flush="true", as it is not a default value. You cannot

use a value of
false. Use the flush attribute exactly as it is given here.

<jsp:param name="parameterName" value={"parameterValue" | <%= expression
%> } />+

The <jsp:param> clause allows you to pass one or more name/value pairs as
parameters to an include
d file. The included file should be dynamic, that is, a JSP file,
servlet, or other file that can process the parameter.

You can use more than one <jsp:param> clause if you want to send more than one
parameter to the included file. The name attribute spe
cifies the parameter name and
takes a case
sensitive literal string. The value attribute specifies the parameter value
and takes either a case
sensitive literal string or an expression that is evaluated at
request time.


Sets a property v
alue or values in a Bean.

JSP Syntax



{ property= "*" |

property="propertyName" [ param="parameterName" ] |

property="propertyName" value="{string | <%= expression %>}"




<jsp:setProperty name="mybean" prope
rty="*" />

<jsp:setProperty name="mybean" property="username" />

<jsp:setProperty name="mybean" property="username" value="Steve" />

The <jsp:setProperty> element sets the value of one or more properties in a
Bean, using the Bean’s setter methods. You mus
t declare the Bean with <jsp:useBean>
before you set a property value with <jsp:setProperty>. Because <jsp:useBean> and
<jsp:setProperty> work together, the Bean

instance names they use must match (that is, the value of name in <jsp:setProperty>
and the va
lue of id in <jsp:useBean> must be the same).

You can use <jsp:setProperty> to set property values in several ways:

By passing all of the values the user enters (stored as parameters in the request
object) to matching properties in the Bean

By passing a sp
ecific value the user enters to a specific property in the Bean

By setting a Bean property to a value you specify as either a String or an expression
that is evaluated at runtime

Each method of setting property values has its own syntax, as described in t
he next

Attributes and Usage


The name of an instance of a Bean that has already been created or located with a
<jsp:useBean> element. The value of name must match the value of id in
<jsp:useBean>. The <jsp:useBean> elemen
t must appear before <jsp:seProperty> in
the JSP file.


Stores all of the values the user enters in the viewable JSP page (called request
parameters) in matching Bean properties. The names of the properties in the Bean must
match the names of t
he request parameters, which are usually the elements of an HTML
form. A Bean property is usually defined by a variable declaration with matching getter
and setter methods (for more information, see the JavaBeans

API Specification available at

The values of the request parameters sent from the client to the server are always of
type String. The String values are converted to other data types so they can be stored in
Bean properties.

rty="propertyName" [ param="parameterName"]

Sets one Bean property to the value of one request parameter. In the syntax,
property specifies the name of the Bean property and param specifies the name of the
request parameter by which data is being sent from

the client to the server. If the Bean
property and the request parameter have different names, you must specify both
property and param. If they have the same name, you can specify

property and omit param. If a parameter has an empty or null value, the co
Bean property is not


property="propertyName" value="{string | <%= expression %>}"

Sets one Bean property to a specific value. The value can be a String or an
expression that is evaluated at runtime. If the value is a String, is an expressi
on, its
value must have a data type that matches the the data type of the value of the
expression must match the data type of the Bean property.

If the parameter has an empty or null value, the corresponding Bean property is not set.
You cannot use both th
e param and value attributes in a <jsp:setProperty> element.


Locates or instantiates a Bean with a specific name and scope.

JSP Syntax




{ class="package.class" |

pe="package.class" |

class="package.class" type="package.class" |

beanName="{package.class | <%= expression %>}" type="package.class"


{ /> |

> other elements </jsp:useBean>



<jsp:useBean id="cart" scope="session" class="session.Carts" />

operty name="cart" property="*" />

<jsp:useBean id="checking" scope="session" class="bank.Checking" >

<jsp:setProperty name="checking" property="balance" value="0.0" />


The <jsp:useBean> element locates or instantiates a JavaBeans component
<jsp:useBean> first attempts to locate an instance of the Bean. If the Bean does not
exist, <jsp:useBean> instantiates it from a class or serialized template.

To locate or instantiate the Bean, <jsp:useBean> takes the following steps, in this

1. A
ttempts to locate a Bean with the scope and name you specify.

2. Defines an object reference variable with the name you specify.

3. If it finds the Bean, stores a reference to it in the variable. If you specified type, gives
the Bean that type.

4. If it do
es not find the Bean, instantiates it from the class you specify, storing a
reference to it in the new variable. If the class name represents a serialized template,
the Bean is instantiated by java.beans.Beans.instantiate.

5. If <jsp:useBean> has instantia
ted (rather than located) the Bean, and if it has body
tags or elements (between <jsp:useBean> and </jsp:useBean>), executes the body
tags. The body of a <jsp:useBean> element often contains a <jsp:setProperty>
element that sets property values in the Bean
. As described in Step 5, the body tags are
only processed if <jsp:useBean> instantiates the Bean. If the Bean already

exists and <jsp:useBean> locates it, the body tags have no effect. In this release, you
can use a <jsp:useBean> element to locate or inst
antiate a Bean, but not an enterprise
bean. To create enterprise beans, you can write a <jsp:useBean> element that calls a
Bean that in turn calls the enterprise bean, or

you can write a custom tag that calls an enterprise bean directly.

Attributes and Us


A variable that identifies the Bean in the scope you specify. You can use the variable
name in expressions or scriptlets in the JSP file. The name is case sensitive and must
conform to the naming conventions of the

scripting langu
age used in the JSP page. If you use the Java programming language, the
conventions in the Java Language Specification. If the Bean has already been created by
another <jsp:useBean> element, the value of id must match the value of id used in the
original <
jsp:useBean> element.


The scope in which the Bean exists and the variable named in id is available. The default
value is page. The meanings of the different scopes are shown below: page You can use
the Bean within t
he JSP page with the

<jsp:useBean> element or any of the page’s static include files, until the page sends a
response back to the client or forwards a request to another file.

request You can use the Bean from any JSP page processing the same request, unti
l a
JSP page sends a response to the client or forwards the request to another file. You can
use the request object to access the Bean, for example, request.getAttribute
(beanInstanceName).session You can use the Bean from any JSP page in the same
as the JSP page that created the Bean. The Bean exists across the entire
session, and any page that participates in the session can use it. The page in which you
create the Bean must have a <%@ page %> directive with session=true. application
You can use
the Bean from any JSP page in the same application as the JSP page that
created the Bean. The Bean exists across an entire JSP application, and any page in the
application can use the Bean.


Instantiates a Bean from a class, using the
new keyword and the class constructor. The
class must not be abstract and must have a public, no
argument constructor. The
package and class name are case sensitive.


If the Bean already exists in the scope, gives the Bean a data type o
ther than the class
from which it was instantiated. If you use type without class or beanName, no Bean is
instantiated. The package and class name are case sensitive.

class="package.class" type="package.class"

Instantiates a Bean from the class named in cl
ass and assigns the Bean the data type
you specify in type. The value of type can be the same as class,a superclass of class, or
an interface implemented by class.

The class you specify in class must not be abstract and must have a public, no
tructor. The package and class names you use with both class and type are case

beanName="{ package.class | <%= expression %> }" type="package.class"

Instantiates a Bean from either a class or a serialized template, using the java.
stantiate method, and gives the Bean the type specified in type. The
Beans.instantiate method checks whether a name represents a class or a serialized
template. If the Bean is serialized, Beans.instantiate reads the serialized form (with a
name like packag
e.class.ser) using a class loader.