Java Server Pages
Java Server Pages
JavaServer Pages simplify the delivery of dynamic Web content. They enable Web application programmers to create
dynamic content by reusing predefined components and by interacting with components using server-side scripting.
In addition to the classes and interfaces for programming servlets (from packages javax.servlet and
javax.servlet.http), classes and interfaces specific to JavaServer Pages programming are located in packages
javax.servlet.jsp and javax.servlet.jsp.tagext.
In late 1999, Sun Microsystems added a new element to the collection of Enterprise Java tools: JavaServer Pages
(JSP). JavaServer Pages are built on top of Java servlets and are designed to increase the efficiency in which
programmers, and even nonprogrammers, can create web content.
What is JSP?
JavaServer Pages is a technology for developing web pages that include dynamic content. Unlike a plain HTML page,
which contains static content that always remains the same, a JSP page can change its content based on any number
of variable items, including the identity of the user, the user's browser type, information provided by the user, and
selections made by the user.
A JSP page contains standard markup language elements, such as HTML tags, just like a regular web page. However,
a JSP page also contains special JSP elements that allow the server to insert dynamic content in the page. JSP
elements can be used for a variety of purposes, such as retrieving information from a database or registering user
preferences. When a user asks for a JSP page, the server executes the JSP elements, merges the results with the
static parts of the page, and sends the dynamically composed page back to the browser, as illustrated in Figure-1.
JSP defines a number of standard elements that are useful for any web application, such as accessing JavaBeans
components, passing control between pages and sharing information between requests, pages, and users.
Programmers can also extend the JSP syntax by implementing application-specific elements that perform tasks such
as accessing databases and Enterprise JavaBeans, sending email, and generating HTML to present application-specific
data. One such set of commonly needed custom elements is defined by a specification related to the JSP
specification: the JSP Standard Tag Library (JSTL) specification. The combination of standard elements and custom
elements allows for the creation of powerful web applications.
JSP Overview
A JSP page is simply a regular web page with JSP elements for generating the parts that differ for each request, as
shown in Figure-2.
In many ways, Java Server Pages look like standard XHTML or XML documents. In fact, JSPs normally include XHTML
or XML markup. Such markup is known as fixed-template data or fixed-template text or template text. Fixed-
template data often help a programmer decide whether to use a servlet or a JSP. Programmers tend to use JSPs
when most of the content sent to the client is fixed template data and only a small portion of the content is
generated dynamically with Java code. Programmers use servlets when only a small portion of the content sent to
the client is fixed-template data. In fact, some servlets do not produce content. Rather, they perform a task on behalf
of the client, and then invoke other servlets or JSPs to provide a response. Note that in most cases, servlet and JSP
Page 1
JavaServer Pages (JSP)
technologies are interchangeable. As with servlets, JSPs normally execute as part of a Web server. The server often is
referred to as the JSP container.
<jsp:useBean
id=”userInfo”
class=”com.ora.jsp.beans.userinfo.UserInfoBean”> JSP element
<jsp:setProperty name=”userInfo” property=”*”/>
</jsp:useBean>
<jsp:getProperty name=userInfo”
Property=”userName”/>
JSP element
</ul>
</body> Template text
</html>
Page 2
JavaServer Pages (JSP)
Instantiation:
When a web container receives a JSP request (may be first or subsequent), it checks for the JSP’s servlet instance. If
no servlet instance is available or if it is older than the JSP, then, the web container creates the servlet instance using
following stages.
• Translation
• Compilation
• Loading
• Instantiation
• Initialization
Translation
Web container translates (converts) the jsp code into a servlet code. This means that JSP is actually a servlet. After
this stage, there is no JSP, everything is a servlet. This task will create a complete JSP page, by considering all
included components. Here on, the static content and dynamic contents are treated differently.
The resultant is a java class instead of an html page (which we wrote). This is how the structure of a jsp compiled
into a java class will be.
package org.apache.jsp.WEB_002dINF.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class firstJsp_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory =
JspFactory.getDefaultFactory();
............
............
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
............
............
}
public void _jspDestroy() {
............
Page 3
JavaServer Pages (JSP)
}
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws java.io.IOException, ServletException {
............
............
}
............
............
}
When a JSP-enabled server receives the first request for a JSP, the JSP container translates that JSP into a Java
servlet that handles the current request and future requests to the JSP. If there are any errors compiling the new
servlet, these errors result in translation-time errors. The JSP container places the Java statements that implement
the JSP’s response in method _jspService at translation time. If the new servlet compiles properly, the JSP
container invokes method _jspService to process the request. The JSP may respond directly to the request or
may invoke other Web application components to assist in processing the request. Any errors that occur during
request processing are known as request-time errors.
Overall, the request/response mechanism and life cycle of a JSP is the same as that of a servlet. JSPs can define
methods jspInit and jspDestroy (similar to servlet methods init and destroy), which the JSP container
invokes when initializing a JSP and terminating a JSP, respectively. JSP programmers can define these methods
using JSP declarations—part of the JSP scripting mechanism.
Compilation:
The generated servlet is compiled to validate the syntax. As it is a java class, the compilation is done using javac
command. This will generate the byte code to be run on JVM.
Loading:
The compiled byte code is loaded by the class loader used by web container. This is a standard process of using any
java class.
Instantiation:
In this step, instance of the servlet class is created so that it can serve the request.
Initialization:
Initialization is done by calling the jspInit() method. This is one time activity at the start of the initialization process.
Initialization will make the ServletContext and ServletConfig objects available. One can access many attributes
related to the web container and the servlet itself. After initialization the servlet is ready to process requests.
Request Processing:
Entire initialization process is done to make the servlet available in order to process the incoming request.
jspService() is the method that actually processes the request. It prints the response in html (any other)
format, using ‘out’ object.
Destroy:
Whenever the server is shutting down or when the server needs memory, the server removes the instance of the
servlet. The destroy method jspDestroy() can be called by the server after initialization and before or after
request processing. Once destroyed the jsp needs to be initialized again.
Just to summarize, web container handles incoming requests to a jsp by converting it into a servlet and then by using
this servlet to generate the response. Also when the server shuts down, the container needs to clear the instances.
Page 4
JavaServer Pages (JSP)
JSP Architecture
JSPs
JSPs are
are built
built on
on top
top of
of SUN
SUN Microsystems'
Microsystems' servlet
servlet technology. JSPs areare essential
essential an an HTML
HTML page
page with
with special
special JSP
JSP tags
tags
embedded.
embedded. These
These JSPJSP tags
tags can
can contain
contain Java code. The JSP file extension
extension is
is .jsp
.jsp rather
rather than
than .htm
.htm oror .html.
.html. ThThe
The JSP
engine
engine parses
parses the
the .jsp
.jsp and
and creates
creates aa Java
Java servlet
servlet source file. It then compiles
compiles the the source
source file
file into
into aa class
class file;
file; this
this is
is
done
done the
the first
first time
time and
and this
this why
why the
the JSP
JSP is
is probably
probably slower the first time
time itit is
is accessed.
accessed. Any
Any time
time after
after this
this the
the special
special
comp
compiled
iled servlet is executed and is therefore returns faster.
Figure
Figure--4
4:: JSP Architecture
1. The
The user
user goes
goes to
to aa web
web site
site made
made using
using JSP.
JSP. The user goes to a JSP page page (ending
(ending with
with .jsp).
.jsp). The
The web
web browser
browser
makes the request via the Internet.
2. The JSP request gets sent to the Web server.
3. The Web server recognizes that the file required is special (.jsp (.jsp)),, therefore passes the JSP file to the JSP
Servlet Engine.
4. If the JSP file has been called the first time, the JSP file is parsed, otherwise go to step 7.
5. The next step is to generate a special Servlet from the JSP file. The entire HTML required is conv converted
erted to
println statements.
6. The Servlet source code is compiled into a class.
7. The Servlet is instantiated, calling the init and service methods.
8. HTML from the Servlet output is sent via the Internet.
9. HTML results are displayed on the user's web browser.
Page 5
JavaServer Pages (JSP)
Typically, JSP pages are subject to a translation phase and a request processing phase. The translation phase is
carried out only once, unless the JSP page changes, in which case it is repeated. Assuming there were no syntax
errors within the page, the result is a JSP page implementation class file that implements the Servlet interface, as
shown below.
The translation phase is typically carried out by the JSP engine itself, when it receives an incoming request for the JSP
page for the first time. Note that the JSP 1.1 specification also allows for JSP pages to be precompiled into class files.
Precompilation may be especially useful in removing the start-up lag that occurs when a JSP page delivered in source
form receives the first request from a client. Many details of the translation phase, like the location where the source
and class files are stored are implementation dependent. The source for the class file generated by Tomcat for this
example JSP page (shown in the above figure) is as follows:
package jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.Vector;
import org.apache.jasper.runtime.*;
import java.beans.*;
import org.apache.jasper.JasperException;
import java.text.*;
import java.util.*;
static {
}
public _0005cjsp_0005cjsptest_0002ejspjsptest_jsp_0( ) {
}
Page 6
JavaServer Pages (JSP)
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
// begin
out.write("\r\n<html>\r\n<body>\r\n");
// end
// begin [file="E:\\jsp\\jsptest.jsp";from=(3,2);to=(5,0)]
Date d = new Date();
String today = DateFormat.getDateInstance().format(d);
// end
// begin
out.write("\r\nToday is: \r\n<em> ");
// end
// begin [file="E:\\jsp\\jsptest.jsp";from=(7,8);to=(7,13)]
out.print(today);</b>
// end
// begin
out.write(" </em>\r\n</body>\r\n</html>\r\n");
// end
} catch (Exception ex) {
if (out.getBufferSize() != 0)
out.clear();
pageContext.handlePageException(ex);
} finally {
out.flush();
_jspxFactory.releasePageContext(pageContext);
}
}
}
The JSP page implementation class file extends HttpJspBase, which in turn implements the Servlet interface.
Observe how the service method of this class, _jspService(), essentially inlines the contents of the JSP page.
Page 7
JavaServer Pages (JSP)
Although _jspService() cannot be overridden, the developer can describe initialization and destroy events by
providing implementations for the jspInit() and jspDestroy() methods within their JSP pages.
Once this class file is loaded within the servlet container, the _jspService() method is responsible for replying
to a client's request. By default, the _jspService() method is dispatched on a separate thread by the servlet
container in processing concurrent client requests, as shown below:
Object Scopes
Before we look at JSP syntax and semantics, it is important to understand the scope or visibility of Java objects within
JSP pages that are processing a request. Objects may be created implicitly using JSP directives, explicitly through
actions, or, in rare cases, directly using scripting code. The instantiated objects can be associated with a scope
attribute defining where there is a reference to the object and when that reference is removed. The following
diagram indicates the various scopes that can be associated with a newly created object:
Page 8
JavaServer Pages (JSP)
Implicit Objects
Implicit objects provide programmers with access to many servlet capabilities in the context of a JavaServer Page.
Implicit objects have four scopes:
• Application,
• Page,
• Request and
• Session
The JSP and servlet container application owns objects with application scope. Any servlet or JSP can manipulate
such objects. Objects with page scope exist only in the page that defines them. Each page has its own instances of
the page-scope implicit objects. Objects with request scope exist for the duration of the request. For example, a JSP
can partially process a request, and then forward the request to another servlet or JSP for further processing.
Request-scope objects go out of scope when request processing completes with a response to the client. Objects
with session scope exist for the client’s entire browsing session. Figure-8 describes the JSP implicit objects and their
scopes.
exception This java.lang.Throwable object represents the exception that is passed to the JSP error
page. This object is available only in a JSP error page.
page This java.lang.Object object represents the this reference for the current JSP
instance.
response This object represents the response to the client. The object normally is an instance of a class
that implements HttpServletResponse (package javax.servlet.http). If a
protocol other than HTTP is used, this object is an instance of a class that implements
javax.servlet.ServletResponse.
Request Scope
request This object represents the client request. The object normally is an instance of a class that
implements HttpServletRequest (package javax.servlet.http). If a protocol
other than HTTP is used, this object is an instance of a subclass of
javax.servlet.ServletRequest.
Session Scope
Page 9
JavaServer Pages (JSP)
JSP Elements
The JSP code for the application will consist of the following tags or elements.
<%@ %> Directives Control the structure of the servlet and serve as mere messages for the JSP
engine specifying actions for the particular JSP page.
<%! %> Declarations Define variables and methods. All declarative statements in a JSP page should
end with semicolon.
<%= %> Expressions Specify statements that evaluated and displayed in the output.
<jsp: > Actions Insert a file, reuse bean, or forward the script control to HTML.
Figure-9: JSP Elements
JSP Comments
A comment marks text or lines that the JSP container should ignore. A comment is useful when you want to
comment out part of your JSP page. The JSP container does not process anything within the <%-- and --%>
characters or within the <!-- and --> characters. A comment is not inserted into the response. In Jsp two types of
comments are allowed in the Jsp page:
JSP Directives
JSP directives are as a message from a JSP page to the JSP container that controls the processing of the entire page.
JSP directives control how the JSP compiler generates the servlet. Actually a directive is a way for you to give special
instruction to the container at page translation time. Directives (delimited by <%@ and %>) are processed at
translation time. Thus, directives do not produce any immediate output, because they are processed before the JSP
accepts any requests. Figure-10 summarizes the three directive types.
Page 10
JavaServer Pages (JSP)
Directive Description
include Causes the JSP container to perform a translation-time insertion of another resource’s content. As
the JSP is translated into a servlet and compiled, the referenced file replaces the include
directive and is translated as if it were originally part of the JSP.
taglib Allows programmers to include their own new tags in the form of tag libraries. These libraries can
be used to encapsulate functionality and simplify the coding of a JSP.
Figure-10: JSP directives
page Directive
The page directive specifies global settings for the JSP in the JSP container. There can be many page directives,
provided that there is only one occurrence of each attribute. The only exception to this rule is the import attribute,
which can be used repeatedly to import Java packages used in the 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 include file is a file whose content becomes part of the calling JSP file. The <%@
page %> directive does not apply to any dynamic include files. No matter where you position the <%@ page
%> directive in a JSP file or included files, it applies to the entire translation unit. However, it is often good
programming style to place it at the top of the JSP file.
Syntax
<%@ page
[ language="java" ]
[ extends="package.class" ]
[ import="{package.class | package.*}, ..." ]
[ session="true | false" ]
[ buffer="none | 8kb | sizekb" ]
[ autoFlush="true | false" ]
[ isThreadSafe="true | false" ]
[ info="text" ]
[ errorPage="relativeURL" ]
[ contentType="mimeType[;charset=characterSet ]"|"text/html;charset=ISO-8859-1" ]
[ isErrorPage="true | false" ]
%>
extends extends="package.class"
Specifies the class from which the translated JSP will be inherited. This attribute must be a fully
qualified package and class name.
Page 11
JavaServer Pages (JSP)
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:
java.lang.*
javax.servlet.*
javax.servlet.jsp.*
javax.servlet.http.*
You must place the import attribute before the element that calls the imported class.
info info="text"
Specifies an information string that describes the page. This string is returned by the
getServletInfo method of the servlet that represents the translated JSP. This method can
be invoked through the JSP’s implicit page object.
errorPage errorPage="relativeURL"
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 resolved by the Web
server. If not, the pathname is relative to the current JSP file.
Any exceptions in the current page that are not caught are sent to the error page for processing.
The error page implicit object exception references the original exception.
Page 12
JavaServer Pages (JSP)
Examples
<%@ page import="java.util.*, java.lang.*" %>
<%@ page buffer="5kb" autoFlush="false" %>
<%@ page errorPage="error.jsp" %>
include Directive
The <%@ include %> directive inserts a file of text or code in a JSP file at translation 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 file. 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.
You can only use include to include static files. This means that the parsed result of the included file is added to
the JSP file where the <%@ include %> directive is placed. Once the included file is parsed and included,
processing resumes with the next line of the calling 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 language.
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.
Some of the behaviours of the <%@ include %> directive depend on the particular JSP container you are using,
for example:
• The included file might be open and available to all requests, or it might have security restrictions.
• The JSP page might be recompiled if the included file changes.
The difference between directive include and action <jsp:include> is noticeable only if the included content
changes. For example, if the definition of an XHTML document changes after it is included with directive include,
future invocations of the JSP will show the original content of the XHTML document, not the new content. In
contrast, action <jsp:include> is processed in each request to the JSP. Therefore, changes to included content
would be apparent in the next request to the JSP that uses action <jsp:include>.
Syntax
<%@ include file="relativeURL" %>
Attributes
file="relativeURL"
Page 13
JavaServer Pages (JSP)
The pathname to the included file, which is always a relative URL. Simply put, a relative URL is just the path
segment of an URL, without a protocol, port, or domain name, like this:
"error.jsp""/templates/onlinestore.html""/beans/calendar.jsp"
If the relative URL starts with /, the path is relative to the JSP application's context, which is a
javax.servlet.ServletContext object that is in turn stored in the application object. If the relative URL
starts with a directory or file name, the path is relative to the JSP file.
taglib Directive
It defines a tag library and prefix for the custom tags used in the JSP page. The <%@ taglib %> directive declares
that the JSP file uses custom tags, names the tag library that defines them, 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 defined in each must be unique.
JSP Syntax
<%@ taglib uri="URIToTagLibrary" prefix="tagPrefix" %>
Attributes
uri="URIToTagLibrary"
The Uniform Resource Identifier (URI) that uniquely names the set of custom tags associated with the named
tag prefix. A URI can be any of the following:
• A Uniform Resource Locator (URL), as defined in RFC 2396, available at
http://www.hut.fi/u/jkorpela/rfc/2396/full.html
• A Uniform Resource Name (URN), as defined in RFC 2396
• An absolute or relative pathname
prefix="tagPrefix"
The prefix that precedes the custom tag name, for example, 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.
Examples
<%@ taglib uri="http://www.jspcentral.com/tags" prefix="public" %>
<public:loop>
.
.
</public:loop>
JSP Declaration
A declaration declares one or more variables or methods that you can use in JavaTM code later in the JSP file. You
must declare the variable or method before you use it in the JSP file.
Page 14
JavaServer Pages (JSP)
You can declare any number of variables or methods within one declaration element, as long as you end each
declaration with a semicolon. The declaration must be valid in the Java programming language.
When you write a declaration 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.
A declaration has translation unit scope, so it is valid in the JSP page and any of its static include 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>.
JSP Syntax
<%! declaration; [ declaration; ]+ ... %>
Examples
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
Return x*x;
%>
JSP Scriptlet
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.
Page 15
JavaServer Pages (JSP)
• Write 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 you write 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.
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" )) {
%>
JSP Expression
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.
When you write expressions in a JSP file, remember these points:
• You 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.
You 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.
JSP Syntax
<%= expression %>
Examples
The map file has <font color="blue"><%= map.size() %></font> entries.
Good guess, but nope. Try <b><%= numguess.getHint() %></b>.
JSP Actions
These actions provide JSP implementors with access to several of the most common tasks performed in a JSP, such as
including content from other resources, forwarding requests to other resources and interacting with JavaBeans. JSP
Page 16
JavaServer Pages (JSP)
containers process actions at request time. Actions are delimited by <jsp:action> and </jsp:action>,
where action is the standard action name. In cases where nothing appears between the starting and ending tags,
the XML empty element syntax <jsp:action /> can be used. Figure-12 summarizes the JSP standard actions.
Action Description
<jsp:include> Dynamically includes another resource in a JSP. As the JSP executes, the referenced
resource is included and processed.
<jsp:forward> Forwards request processing to another JSP, servlet or static page. This action terminates
the current JSP’s execution.
<jsp:param> Used with the include, forward and plugin actions to specify additional
name/value pairs of information for use by these actions.
JavaBean Manipulation
<jsp:useBean> Specifies that the JSP uses a JavaBean instance. This action specifies the scope of the
bean and assigns it an ID that scripting components can use to manipulate the bean.
<jsp:setProperty> Sets a property in the specified JavaBean instance. A special feature of this action is
automatic matching of request parameters to bean properties of the same name.
<jsp:getProperty> Gets a property in the specified JavaBean instance and converts the result to a string for
output in the response.
Figure-12: JSP Standard Actions
<jsp:include> Action
JavaServer Pages support two include mechanisms—the <jsp:include> action and the include directive.
Action <jsp:include> enables dynamic content to be included in a JavaServer Page. If the included resource
changes between requests, the next request to the JSP containing the <jsp:include> action includes the new
content of the resource. On the other hand, the include directive copies the content into the JSP once, at JSP
translation time. If the included resource changes, the new content will not be reflected in the JSP that used the
include directive unless that JSP is recompiled.
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 dynamic. 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.
Page 17
JavaServer Pages (JSP)
JSP Syntax
<jsp:include page="{relativeURL | <%= expression%>}" flush="true" />
or
<jsp:include page="{relativeURL | <%= expression %>}" flush="true" >
<jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />+
</jsp:include>
Figure-13 describes the attributes of action <jsp:include>.
Attribute Description
page page="{relativeURL | <%= expression %>}"
Specifies the relative URI path of the resource to include. The resource must be part of the same Web
application.
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-it cannot contain a protocol name, port number, or domain
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 server.
flush flush="true"
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. Specifies whether the buffer should be flushed after the
include is performed. In JSP 1.1, this attribute is required to be true. Not specifying the
<jsp:include> action’s flush attribute is a translation-time error. Specifying this attribute is
mandatory.
Figure-13: Action <jsp:include> Attributes
Examples
<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" />
</jsp:include>
<jsp:forward> Action
The <jsp:forward> element forwards the request object containing the client request information 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
are not processed.
Page 18
JavaServer Pages (JSP)
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.
Be careful when using <jsp:forward> with unbuffered output. If you have used the <%@ page %> directive
with buffer=none to specify that the output of your JSP file should not be buffered, and if the JSP file has any
data in the out object, using <jsp:forward> will cause an IllegalStateException.
JSP Syntax
<jsp:forward page={"relativeURL" | "<%= expression %>"} />
or
<jsp:forward page={"relativeURL" | "<%= expression %>"} >
<jsp:param name="parameterName"
value="{parameterValue | <%= expression %>}" />+
</jsp:forward>
Attributes
• 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 absolute 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.
You can use more than one <jsp:param> clause if you need to send more than one parameter to the
target file. The name attribute specifies the parameter name and takes a case-sensitive literal string as a
value. The value attribute specifies the parameter value and takes either a case-sensitive literal string or an
expression that is evaluated at request time.
Examples
<jsp:forward page="/servlet/login" />
<jsp:forward page="/servlet/login">
<jsp:param name="username" value="jsmith" />
</jsp:forward>
JavaServer Page forward1.jsp is shown in Figure-14. The primary difference is in lines 22–25 in which
JavaServer Page forward1.jsp forwards the request to JavaServer Page forward2.jsp (Figure-15). Notice the
<jsp:param> action in lines 23–24. This action adds a request parameter representing the date and time at which
the initial request was received to the request object that is forwarded to forward2.jsp.
The <jsp:param> action specifies name/value pairs of information that are passed to the <jsp:include>,
<jsp:forward> and <jsp:plugin> actions. Every <jsp:param> action has two required attributes: name
and value. If a <jsp:param> action specifies a parameter that already exists in the request, the new value for
the parameter takes precedence over the original value. All values for that parameter can be obtained by using the
JSP implicit object request’s getParameterValues method, which returns an array of Strings.
JSP forward2.jsp uses the name specified in the <jsp:param> action ("date") to obtain the date and time. It
also uses the firstName parameter originally passed to forward1.jsp to obtain the user’s first name. JSP
Page 19
JavaServer Pages (JSP)
expressions in Figure-15 (lines 23 and 31) insert the request parameter values in the response to the client. The
screen capture in Figure-14 shows the initial interaction with the client. The screen capture in Figure-15 shows the
results returned to the client after the request was forwarded to forward2.jsp.
Page 20
JavaServer Pages (JSP)
3. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4.
5. <!-- forward2.jsp -->
6.
7. <html xmlns = "http://www.w3.org/1999/xhtml"v
8.
9. <head>
10. <title>Processing a forwarded request</title>
11.
12. <style type = "text/css">
13. .big {
14. font-family: tahoma, helvetica, arial, sans-serif;
15. font-weight: bold;
16. font-size: 2em;
17. }
18. </style>
19. </head>
20.
21. <body>
22. <p class = "big">
23. Hello <%= request.getParameter( "firstName" ) %>, <br />
24. Your request was received <br /> and forwarded at
25. </p>
26.
27. <table style = "border: 6px outset;">
28. <tr>
29. <td style = "background-color: black;">
30. <p class = "big" style = "color: cyan;">
31. <%= request.getParameter( "date" ) %>
32. </p>
33. </td>
34. </tr>
35. </table>
36. </body>
37.
38. </html>
Figure-15: JSP forward2.jsp receives a request (from forward1.jsp in this example) and uses the request parameters as part of
the response to the client
<jsp:plugin> Action
The <jsp:plugin> element plays or displays an object (typically an applet or Bean) in the client Web browser,
using a Java plug-in that is built in to the browser or downloaded from a specified URL.
When the JSP file is translated and compiled and Java and sends back an HTML response to the client, the
<jsp:plugin> element is replaced by either an <object> or <embed> element, according to the browser version.
The <object> element is defined in HTML 4.0 and <embed> in HTML 3.2.
In general, the attributes to the <jsp:plugin> element specify whether the object is a Bean or an applet, locate
the code that will be run, position the object in the browser window, specify an URL from which to download the
plug-in software, and pass parameter names and values to the object.
JSP Syntax
<jsp:plugin
type="bean | applet"
code="classFileName"
codebase="classFileDirectoryName"
Page 21
JavaServer Pages (JSP)
[ name="instanceName" ]
[ archive="URIToArchive, ..." ]
[ title="text" ]
[ align="bottom | top | middle | left | right" ]
[ height="displayPixels" ]
[ width="displayPixels" ]
[ hspace="leftRightPixels" ]
[ vspace="topBottomPixels" ]
[ jreversion="JREVersionNumber | 1.1" ]
[ nspluginurl="URLToPlugin" ]
[ iepluginurl="URLToPlugin" ] >
[ <jsp:params>
[ <jsp:param name="parameterName" value="{parameterValue | <%= expression
%>}" /> ]+
</jsp:params> ]
</jsp:plugin>
Code code="classFileName"
The name of the Java class file the plug-in will execute. You must include the .class extension in
the name. The file you specify should be in the directory named in the codebase attribute.
Codebase codebase="classFileDirectoryName"
The directory (or path to the directory) that contains the Java class file the plug-in will execute. If
you do not supply a value, the path of the JSP file that calls <jsp:plugin> is used.
Page 22
JavaServer Pages (JSP)
used by the component. Such an archive may include the class specified by the code attribute.
Height height="displayPixels"
The initial height, in pixels, of the image the applet or Bean displays, not counting any windows or
dialog boxes the applet or Bean brings up.
Hspace hspace="leftRightPixels"
The amount of space, in pixels, to the left and right (or top and bottom) of the image the applet or
Bean displays. The value must be a nonzero number. Note that hspace creates space to both the
left and right.
Name name="instanceName"
A name for the instance of the Bean or applet, which makes it possible for applets or Beans called
by the same JSP file to communicate with each other
Vspace vspace="topBottomPixels"
The amount of space, in pixels, to the left and right (or top and bottom) of the image the applet or
Bean displays. The value must be a nonzero number. Note that vspace creates space to both the
top and bottom.
Title title=”text”
Text that describes the component.
Width width="displayPixels"
The initial width, in pixels, of the image the applet or Bean displays, not counting any windows or
dialog boxes the applet or Bean brings up.
nspluginurl nspluginurl="URLToPlugin"
The URL where the user can download the JRE plug-in for Netscape Navigator. The value is a full
URL, with a protocol name, optional port number, and domain name.
iepluginurl iepluginurl="URLToPlugin"
The URL where the user can download the JRE plug-in for Internet Explorer. The value is a full URL,
with a protocol name, optional port number, and domain name.
Figure 16
<jsp:params>
[ <jsp:param name="parameterName" value="{parameterValue | <%= expression %>}"
/> ]+
</jsp:params>
The parameters and values that you want to pass to the applet or Bean. To specify more than one parameter
value, you can use more than one <jsp:param> element within the <jsp:params> element.
The name attribute specifies 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 runtime.
Page 23
JavaServer Pages (JSP)
If the dynamic file you are passing the parameter to is an applet, it reads the parameter with the
java.applet.Applet.getParameter method.
Example
Figure-17 defines an applet that draws a picture using the Java2D API. The applet has three parameters that enable
the JSP implementor to specify the background color for the drawing. The parameters represent the red, green and
blue portions of an RGB color with values in the range 0–255. The applet obtains the parameter values in lines 21–
23. If any exceptions occur while processing the parameters, the exceptions are caught at line 32 and ignored,
leaving the applet with its default white background color.
1. // ShapesApplet.java
2. // Applet that demonstrates a Java2D GeneralPath.
3.
4.
5. // Java core packages
6. import java.applet.*;
7. import java.awt.event.*;
8. import java.awt.*;
9. import java.awt.geom.*;
10.
11. // Java extension packages
12. import javax.swing.*;
13.
14. public class ShapesApplet extends JApplet {
15.
16. // initialize the applet
17. public void init()
18. {
19. // obtain color parameters from XHTML file
20. try {
21. int red = Integer.parseInt( getParameter( "red" ) );
22. int green = Integer.parseInt( getParameter( "green" ) );
23. int blue = Integer.parseInt( getParameter( "blue" ) );
24.
25. Color backgroundColor = new Color( red, green, blue );
26.
27. setBackground( backgroundColor );
28. }
29.
30. // if there is an exception while processing the color
31. // parameters, catch it and ignore it
32. catch ( Exception exception ) {
33. // do nothing
34. }
35. }
36.
37. public void paint( Graphics g )
38. {
39. // create arrays of x and y coordinates
40. int xPoints[] =
41. { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };
42. int yPoints[] =
43. { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };
Page 24
JavaServer Pages (JSP)
44.
45. // obtain reference to a Graphics2D object
46. Graphics2D g2d = ( Graphics2D ) g;
47.
48. // create a star from a series of points
49. GeneralPath star = new GeneralPath();
50.
51. // set the initial coordinate of the GeneralPath
52. star.moveTo( xPoints[ 0 ], yPoints[ 0 ] );
53.
54. // create the star--this does not draw the star
55. for ( int k = 1; k < xPoints.length; k++ )
56. star.lineTo( xPoints[ k ], yPoints[ k ] );
57.
58. // close the shape
59. star.closePath();
60.
61. // translate the origin to (200, 200)
62. g2d.translate( 200, 200 );
63.
64. // rotate around origin and draw stars in random colors
65. for ( int j = 1; j <= 20; j++ ) {
66. g2d.rotate( Math.PI / 10.0 );
67.
68. g2d.setColor(
69. new Color( ( int ) ( Math.random() * 256 ),
70. ( int ) ( Math.random() * 256 ),
71. ( int ) ( Math.random() * 256 ) ) );
72.
73. g2d.fill( star ); // draw a filled star
74. }
75. }
76. }
Figure- 17: An applet to demonstrate <jsp:plugin>
Most Web browsers in use today do not support applets written for the Java 2 platform. Executing such applets in
most of today’s browsers requires the Java Plug-in. Figure-18 uses the <jsp:plugin> action (lines 10–22) to
embed the Java Plug-in. Line 11 indicates the package name and class name of the applet class. Line 12 indicates the
codebase from which the applet should be downloaded. Line 13 indicates that the applet should be 400 pixels
wide and line 14 indicates that the applet should be 400 pixels tall. Lines 16–20 specify the applet parameters. You
can change the background color in the applet by changing the red, green and blue values. Note that the
<jsp:plugin> action requires any <jsp:param> actions to appear in a <jsp:params> action.
1. <!--plugin.jsp -->
2.
3. <html>
4.
5. <head>
6. <title>Using jsp:plugin to load an applet</title>
7. </head>
8.
9. <body>
10. <jsp:plugin type = "applet"
11. code = "com.deitel.advjhtp1.jsp.applet.ShapesApplet"
12. codebase = "/advjhtp1/jsp"
13. width = "400"
14. height = "400">
Page 25
JavaServer Pages (JSP)
15.
16. <jsp:params>
17. <jsp:param name = "red" value = "255" />
18. <jsp:param name = "green" value = "255" />
19. <jsp:param name = "blue" value = "0" />
20. </jsp:params>
21.
22. </jsp:plugin>
23. </body>
24. </html>
Figure 18: Using <jsp:plugin> to embed a Java 2 applet in a JSP
<jsp:useBean> Action
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 order:
1. Attempts 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 does 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 instantiated (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 instantiate 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.
JSP Syntax
<jsp:useBean
id="beanInstanceName"
scope="page | request | session | application"
{
class="package.class" |
type="package.class" |
class="package.class" type="package.class" |
beanName="{package.class | <%= expression %>}" type="package.class"
}
{
/> |
> other elements </jsp:useBean>
}
Page 26
JavaServer Pages (JSP)
Attribute Description
Id id="beanInstanceName"
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 language
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.
class class="package.class"
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.
type type="package.class"
If the Bean already exists in the scope, gives the Bean a data type other 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 class and assigns the Bean the data type you specify in type. The value
of type can be the same as class, a super class of class, or an interface implemented by class.
The class you specify in class must not be abstract and must have a public, no-argument constructor. The package
and class names you use with both class and type are case sensitive.
beanName="{package.class | <%= expression %>}" type="package.class"
Page 27
JavaServer Pages (JSP)
Instantiates a Bean from either a class or a serialized template, using the java.beans.Beans.instantiate
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 package.class.ser) using a class loader. For more information, see the
JavaBeans API Specification.
The value of beanName is either a package and class name or an Expression that evaluates to a package and class
name, and is passed to Beans.instantiate. The value of type can be the same as beanName, a super class
of beanName, or an interface implemented by beanName.
The package and class names you use with both beanName and type are case sensitive.
<jsp:setProperty> Action
The <jsp:setProperty> element sets the value of one or more properties in a Bean, using the Bean's setter
methods. You must 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 value 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 specific 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 the next section.
JSP Syntax
<jsp:setProperty
name="beanInstanceName"
{
property= "*" |
property="propertyName" [ param="parameterName" ] |
property="propertyName" value="{string | <%= expression %>}"
}
/>
Page 28
JavaServer Pages (JSP)
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 corresponding Bean property is not set.
• 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, it is converted to the Bean property's data type. If it is an expression, its
value must have a data type that matches 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
the param and value attributes in a <jsp:setProperty> element.
Examples
<jsp:setProperty name="mybean" property="*" />
<jsp:setProperty name="mybean" property="username" />
<jsp:setProperty name="mybean" property="username" value="Steve" />
<jsp:getProperty> Action
The <jsp:getProperty> 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 retrieves 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.
JSP Syntax
<jsp:getProperty name="beanInstanceName" property="propertyName" />
Attributes
• name="beanInstanceName"
The name of an object (usually an instance of a Bean) as declared in a <jsp:useBean> element.
• property="propertyName"
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.
Examples
<jsp:useBean id="calendar" scope="page" class="employee.Calendar" />
<h2>
Calendar of <jsp:getProperty name="calendar" property="username" />
</h2>
Page 29