JSP
Overview
A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format, such as HTML, SVG, WML, and XML; and JSP elements, which construct dynamic content. A syntax card and reference for the JSP elements are available at
http://java.sun.com/products/jsp/technical.html#syntaxThe Web page show below is a form that allows you to select a locale and displays the date in a manner appropriate to the locale.
The source code for this example is in the docs/tutorial/examples/web/date directory created when you unzip the tutorial bundle. The JSP page index.jsp used to create the form appears below; it is a typical mixture of static HTML markup and JSP elements. If you have developed Web pages, you are probably familiar with the HTML document structure statements (<head>, <body>, and so on) and the HTML statements that create a form <form> and a menu <select>. The lines in bold in the example code contains the following types of JSP constructs:
- Directives (<%@page ... %>) import classes in the java.util package and the MyLocales class, and set the content type returned by the page.
- The jsp:useBean element creates an object containing a collection of locales and initializes a variable that points to that object.
- Scriptlets (<% ... %> ) retrieve the value of the locale request parameter, iterate over a collection of locale names, and conditionally insert HTML text into the output.
- Expressions (<%= ... %>) insert the value of the locale name into the response.
- The jsp:include element sends a request to another page (date.jsp) and includes the response in the response from the calling page.
<%@ page import="java.util.*,MyLocales" %> <%@ page contentType="text/html; charset=ISO-8859-5" %> <html> <head><title>Localized Dates</title></head> <body bgcolor="white"> <jsp:useBean id="locales" scope="application" class="MyLocales"/> <form name="localeForm" action="index.jsp" method="post"> <b>Locale:</b> <select name=locale> <% String selectedLocale = request.getParameter("locale"); Iterator i = locales.getLocaleNames().iterator(); while (i.hasNext()) { String locale = (String)i.next(); if (selectedLocale != null && selectedLocale.equals(locale)) { %> <option selected><%=locale%></option> <% } else { %> <option><%=locale%></option> <% } } %> </select> <input type="submit" name="Submit" value="Get Date"> </form> <jsp:include page="date.jsp"/> </body> </html>To build, deploy, and execute this JSP page:
- In a terminal window, go to docs/tutorial/examples/web/date.
- Run ant build. The build target will spawn any necessary compilations and copy files to the docs/tutorial/examples/web/date/build directory.
- Run ant install. The install target notifies Tomcat that the new context is available.
- Open the date URL http://localhost:8080/date.
You will see a combo box whose entries are locales. Select a locale and click Get Date. You will see the date expressed in a manner appropriate for that locale.
The Example JSP Pages
To illustrate JSP technology, this chapter rewrites each servlet in the Duke's Bookstore application introduced in as a JSP page:
Function
JSP Pages
Enter the bookstore
bookstore.jsp
Create the bookstore banner
banner.jsp
Browse the books offered for sale
catalog.jsp
Put a book in a shopping cart
catalog.jsp and bookdetails.jsp
Get detailed information on a specific book
bookdetails.jsp
Display the shopping cart
showcart.jsp
Remove one or more books from the shopping cart
showcart.jsp
Buy the books in the shopping cart
cashier.jsp
Receive an acknowledgement for the purchase
receipt.jsp
The data for the bookstore application is still maintained in a database. However, two changes are made to the database helper object database.BookDB:
- The database helper object is rewritten to conform to JavaBeans component design patterns as described in JavaBeans Component Design Conventions. This change is made so that JSP pages can access the helper object using JSP language elements specific to JavaBeans components.
- Instead of accessing the bookstore database directly, the helper object goes through a data access object database.BookDAO.
The implementation of the database helper object follows. The bean has two instance variables: the current book and a reference to the database enterprise bean.
public class BookDB { private String bookId = "0"; private BookDBEJB database = null; public BookDB () throws Exception { } public void setBookId String(bookId) { this.bookId = bookId; } public void setDatabase(BookDBEJB database) { this.database = database; } public BookDetails getBookDetails() throws Exception { try { return (BookDetails)database. getBookDetails(bookId); } catch (BookNotFoundException ex) { throw ex; } } ... }Finally, this version of the example contains an applet to generate a dynamic digital clock in the banner. See Including an Applet for a description of the JSP element that generates HTML for downloading the applet.
The source code for the application is located in the docs/tutorial/examples/web/bookstore2 directory created when you unzip the tutorial bundle (see Running the Examples). To build, deploy, and run the example:
- In a terminal window, go to docs/tutorial/examples/web/bookstore2.
- Run ant build. The build target will spawn any necessary compilations and copy files to the docs/tutorial/examples/web/bookstore2/build directory.
- Make sure Tomcat is started.
- Run ant install. The install target notifies Tomcat that the new context is available.
- Start the PointBase database server and populate the database if you have not done so already (see Accessing Databases from Web Applications).
- Open the bookstore URL http://localhost:8080/bookstore2/enter.
See Common Problems and Their Solutions and Troubleshooting for help with diagnosing common problems.
The Life Cycle of a JSP Page
A JSP page services requests as a servlet. Thus, the life cycle and many of the capabilities of JSP pages (in particular the dynamic aspects) are determined by Java Servlet technology, and much of the discussion in this chapter refers to functions described in .
When a request is mapped to a JSP page, it is handled by a special servlet that first checks whether the JSP page's servlet is older than the JSP page. If it is, it translates the JSP page into a servlet class and compiles the class. During development, one of the advantages of JSP pages over servlets is that the build process is performed automatically.
Translation and Compilation
During the translation phase each type of data in a JSP page is treated differently. Template data is transformed into code that will emit the data into the stream that returns data to the client. JSP elements are treated as follows:
- Directives are used to control how the Web container translates and executes the JSP page.
- Scripting elements are inserted into the JSP page's servlet class. See JSP Scripting Elements for details.
- Elements of the form <jsp:XXX ... /> are converted into method calls to JavaBeans components or invocations of the Java Servlet API.
For a JSP page named pageName, the source for a JSP page's servlet is kept in the file:
$JWSDP_HOME/work/Standard Engine/ localhost/context_root/pageName$jsp.javaFor example, the source for the index page named(index.jsp) for the date localization example discussed at the beginning of the chapter would be named:
$JWSDP_HOME/work/Standard Engine/ localhost/date/index$jsp.javaBoth the translation and compilation phases can yield errors that are only observed when the page is requested for the first time. If an error occurs while the page is being translated (for example, if the translator encounters a malformed JSP element), the server will return a ParseException, and the servlet class source file will be empty or incomplete. The last incomplete line will give a pointer to the incorrect JSP element.
If an error occurs while the JSP page is being compiled (for example, there is a syntax error in a scriptlet), the server will return a JasperException and a message that includes the name of the JSP page's servlet and the line where the error occurred.
Once the page has been translated and compiled, the JSP page's servlet for the most part follows the servlet life cycle described in Servlet Life Cycle:
- If an instance of the JSP page's servlet does not exist, the container
- Loads the JSP page's servlet class
- Instantiates an instance of the servlet class
- Initializes the servlet instance by calling the jspInit method
- The container invokes the _jspService method, passing a request and response object.
If the container needs to remove the JSP page's servlet, it calls the jspDestroy method.
Execution
You can control various JSP page execution parameters by using page directives. The directives that pertain to buffering output and handling errors are discussed here. Other directives are covered in the context of specific page authoring tasks throughout the chapter.
Buffering
When a JSP page is executed, output written to the response object is automatically buffered. You can set the size of the buffer with the following page directive:
<%@ page buffer="none|xxxkb" %>A larger buffer allows more content to be written before anything is actually sent back to the client, thus providing the JSP page with more time to set appropriate status codes and headers or to forward to another Web resource. A smaller buffer decreases server memory load and allows the client to start receiving data more quickly.
Handling Errors
Any number of exceptions can arise when a JSP page is executed. To specify that the Web container should forward control to an error page if an exception occurs, include the following page directive at the beginning of your JSP page:
<%@ page errorPage="file_name" %>The Duke's Bookstore application page initdestroy.jsp contains the directive
<%@ page errorPage="errorpage.jsp"%>The beginning of errorpage.jsp indicates that it is serving as an error page with the following page directive:
<%@ page isErrorPage="true|false" %>This directive makes the exception object (of type javax.servlet.jsp.JspException) available to the error page, so that you can retrieve, interpret, and possibly display information about the cause of the exception in the error page.
Note: You can also define error pages for the WAR that contains a JSP page. If error pages are defined for both the WAR and a JSP page, the JSP page's error page takes precedence.
Initializing and Finalizing a JSP Page
You can customize the initialization process to allow the JSP page to read persistent configuration data, initialize resources, and perform any other one-time activities by overriding the jspInit method of the JspPage interface. You release resources using the jspDestroy method. The methods are defined using JSP declarations, discussed in Declarations.
The bookstore example page initdestroy.jsp defines the jspInit method to retrieve the object database.BookDBAO that accesses the bookstore database and stores a reference to the bean in bookDBAO.
private BookDBAO bookDBAO; public void jspInit() { bookDBAO = (BookDBAO)getServletContext().getAttribute("bookDB"); if (bookDBAO == null) System.out.println("Couldn't get database."); }When the JSP page is removed from service, the jspDestroy method releases the BookDBAO variable.
public void jspDestroy() { bookDBAO = null; }Since the enterprise bean is shared between all the JSP pages, it should be initialized when the application is started, instead of in each JSP page. Java Servlet technology provides application life-cycle events and listener classes for this purpose. As an exercise, you can move the code that manages the creation of the enterprise bean to a context listener class. See Handling Servlet Life Cycle Events for the context listener that initializes the Java Servlet version of the bookstore application.
Creating Static Content
You create static content in a JSP page by simply writing it as if you were creating a page that consisted only of that content. Static content can be expressed in any text-based format, such as HTML, WML, and XML. The default format is HTML. If you want to use a format other than HTML, you include a page directive with the contentType attribute set to the format type at the beginning of your JSP page. For example, if you want a page to contain data expressed in the wireless markup language (WML), you need to include the following directive:
<%@ page contentType="text/vnd.wap.wml"%>A registry of content type names is kept by the IANA at:
ftp://ftp.isi.edu/in-notes/iana/assignments/media-types
Creating Dynamic Content
You create dynamic content by accessing Java programming language objects from within scripting elements.
Using Objects within JSP Pages
You can access a variety of objects, including enterprise beans and JavaBeans components, within a JSP page. JSP technology automatically makes some objects available, and you can also create and access application-specific objects.
Implicit Objects
Implicit objects are created by the Web container and contain information related to a particular request, page, or application. Many of the objects are defined by the Java Servlet technology underlying JSP technology and are discussed at length in . Table 13-2 summarizes the implicit objects.
Variable
Class
Description
application
javax.servlet.ServletContext
The context for the JSP page's servlet and any Web components contained in the same application. See Accessing the Web Context.
config
javax.servlet.ServletConfig
Initialization information for the JSP page's servlet.
exception
java.lang.Throwable
Accessible only from an error page. See Handling Errors.
out
javax.servlet.jsp.JspWriter
The output stream.
page
java.lang.Object
The instance of the JSP page's servlet processing the current request. Not typically used by JSP page authors.
pageContext
javax.servlet.jsp.PageContext
The context for the JSP page. Provides a single API to manage the various scoped attributes described in Using Scope Objects.
This API is used extensively when implementing tag handlers (see Tag Handlers).
request
subtype of javax.servlet.ServletRequest
The request triggering the execution of the JSP page. See Getting Information from Requests.
response
subtype of javax.servlet.ServletResponse
The response to be returned to the client. Not typically used by JSP page authors.
session
javax.servlet.http.HttpSession
The session object for the client. See Maintaining Client State.
Application-Specific Objects
When possible, application behavior should be encapsulated in objects so that page designers can focus on presentation issues. Objects can be created by developers who are proficient in the Java programming language and in accessing databases and other services. There are four ways to create and use objects within a JSP page:
- Instance and class variables of the JSP page's servlet class are created in declarations and accessed in scriptlets and expressions.
- Local variables of the JSP page's servlet class are created and used in scriptlets and expressions.
- Attributes of scope objects (see Using Scope Objects) are created and used in scriptlets and expressions.
- JavaBeans components can be created and accessed using streamlined JSP elements. These elements are discussed in the chapter JavaBeans Components in JSP Pages. You can also create a JavaBeans component in a declaration or scriptlet and invoke the methods of a JavaBeans component in a scriptlet or expression.
Declarations, scriptlets, and expressions are described in JSP Scripting Elements.
Shared Objects
The conditions affecting concurrent access to shared objects described in Controlling Concurrent Access to Shared Resources apply to objects accessed from JSP pages that run as multithreaded servlets. You can indicate how a Web container should dispatch multiple client requests with the following page directive:
<%@ page isThreadSafe="true|false" %>When isThreadSafe is set to true, the Web container may choose to dispatch multiple concurrent client requests to the JSP page. This is the default setting. If using true, ensure that you properly synchronize access to any shared objects defined at the page level. This includes objects created within declarations, JavaBeans components with page scope, and attributes of the page scope object.
If isThreadSafe is set to false, requests are dispatched one at a time, in the order they were received, and access to page level objects does not have to be controlled. However, you still must ensure that access to attributes of the application or session scope objects and to JavaBeans components with application or session scope is properly synchronized.
JSP Scripting Elements
JSP scripting elements are used to create and access objects, define methods, and manage the flow of control. Since one of the goals of JSP technology is to separate static template data from the code needed to dynamically generate content, very sparing use of JSP scripting is recommended. Much of the work that requires the use of scripts can be eliminated by using custom tags, described in Custom Tags in JSP Pages.
JSP technology allows a container to support any scripting language that can call Java objects. If you wish to use a scripting language other than the default, java, specify it in a page directive at the beginning of a JSP page:
<%@ page language="scripting language" %>Since scripting elements are converted to programming language statements in the JSP page's servlet class, import any classes and packages used by a JSP page. If the page language is java, you import a class or package with the page directive:
<%@ page import="packagename.*, fully_qualified_classname" %>For example, the bookstore example page showcart.jsp imports the classes needed to implement the shopping cart with the following directive:
<%@ page import="java.util.*, cart.*" %>
Declarations
A JSP declaration is used to declare variables and methods in a page's scripting language. The syntax for a declaration is as follows:
<%! scripting language declaration %>When the scripting language is the Java programming language, variables and methods in JSP declarations become declarations in the JSP page's servlet class.
The bookstore example page initdestroy.jsp defines an instance variable named bookDBAO and the initialization and finalization methods jspInit and jspDestroy discussed earlier in a declaration:
<%! private BookDBAO bookDBAO; public void jspInit() { ... } public void jspDestroy() { ... } %>
Scriptlets
A JSP scriptlet is used to contain any code fragment that is valid for the scripting language used in a page. The syntax for a scriptlet is as follows:
<% scripting language statements %>When the scripting language is set to java, a scriptlet is transformed into a Java programming language statement fragment and is inserted into the service method of the JSP page's servlet. A programming language variable created within a scriptlet is accessible from anywhere within the JSP page.
The JSP page showcart.jsp contains a scriptlet that retrieves an iterator from the collection of items maintained by a shopping cart and sets up a construct to loop through all the items in the cart. Inside the loop, the JSP page extracts properties of the book objects and formats them using HTML markup. Since the while loop opens a block, the HTML markup is followed by a scriptlet that closes the block.
<% Iterator i = cart.getItems().iterator(); while (i.hasNext()) { ShoppingCartItem item = (ShoppingCartItem)i.next(); BookDetails bd = (BookDetails)item.getItem(); %> <tr> <td align="right" bgcolor="#ffffff"> <%=item.getQuantity()%> </td> <td bgcolor="#ffffaa"> <strong><a href=" <%=request.getContextPath()%>/bookdetails?bookId= <%=bd.getBookId()%>"><%=bd.getTitle()%></a></strong> </td> ... <% // End of while } %>The output appears below:
Expressions
A JSP expression is used to insert the value of a scripting language expression, converted into a string, into the data stream returned to the client. When the scripting language is the Java programming language, an expression is transformed into a statement that converts the value of the expression into a String object and inserts it into the implicit out object.
The syntax for an expression is as follows:
<%= scripting language expression %>Note that a semicolon is not allowed within a JSP expression, even if the same expression has a semicolon when you use it within a scriptlet.
The following scriptlet retrieves the number of items in a shopping cart:
<% // Print a summary of the shopping cart int num = cart.getNumberOfItems(); if (num > 0) { %>Expressions are then used to insert the value of num into the output stream and determine the appropriate string to include after the number:
<font size="+2"> <%=messages.getString("CartContents")%> <%=num%> <%=(num==1 ? <%=messages.getString("CartItem")%> : <%=messages.getString("CartItems"))%></font>
Including Content in a JSP Page
There are two mechanisms for including another Web resource in a JSP page: the include directive and the jsp:include element.
The include directive is processed when the JSP page is translated into a servlet class. The effect of the directive is to insert the text contained in another file-- either static content or another JSP page--in the including JSP page. You would probably use the include directive to include banner content, copyright information, or any chunk of content that you might want to reuse in another page. The syntax for the include directive is as follows:
<%@ include file="filename" %>For example, all the bookstore application pages include the file banner.jsp which contains the banner content, with the following directive:
<%@ include file="banner.jsp" %>In addition, the pages bookstore.jsp, bookdetails.jsp, catalog.jsp, and showcart.jsp include JSP elements that create and destroy a database bean with the following directive:
<%@ include file="initdestroy.jsp" %>Because statically put an include directive in each file that reuses the resource referenced by the directive, this approach has its limitations. For a more flexible approach to building pages out of content chunks, see A Template Tag Library.
The jsp:include element is processed when a JSP page is executed. The include action allows you to include either a static or dynamic resource in a JSP file. The results of including static and dynamic resources are quite different. If the resource is static, its content is inserted into the calling JSP file. If the resource is dynamic, the request is sent to the included resource, the included page is executed, and then the result is included in the response from the calling JSP page. The syntax for the jsp:include element is:
<jsp:include page="includedPage" />Note: Tomcat will not reload a statically included page that has been modified unless the including page is also modified.
The date application introduced at the beginning of this chapter includes the page that generates the display of the localized date with the following statement:
<jsp:include page="date.jsp"/>
Transferring Control to Another Web Component
The mechanism for transferring control to another Web component from a JSP page uses the functionality provided by the Java Servlet API as described in Transferring Control to Another Web Component. You access this functionality from a JSP page with the jsp:forward element:
<jsp:forward page="/main.jsp" />Note that if any data has already been returned to a client, the jsp:forward element will fail with an IllegalStateException.
jsp:param Element
When an include or forward element is invoked, the original request object is provided to the target page. If you wish to provide additional data to that page, you can append parameters to the request object with the jsp:param element:
<jsp:include page="..." > <jsp:param name="param1" value="value1"/> </jsp:include>
Including an Applet
You can include an applet or JavaBeans component in a JSP page by using the jsp:plugin element. This element generates HTML that contains the appropriate client-browser-dependent constructs (<object> or <embed>) that will result in the download of the Java Plug-in software (if required) and client-side component and subsequent execution of any client-side component. The syntax for the jsp:plugin element is as follows:
<jsp:plugin type="bean|applet" code="objectCode" codebase="objectCodebase" { align="alignment" } { archive="archiveList" } { height="height" } { hspace="hspace" } { jreversion="jreversion" } { name="componentName" } { vspace="vspace" } { width="width" } { nspluginurl="url" } { iepluginurl="url" } > { <jsp:params> { <jsp:param name="paramName" value= paramValue" /> }+ </jsp:params> } { <jsp:fallback> arbitrary_text </jsp:fallback> } </jsp:plugin>The jsp:plugin tag is replaced by either an <object> or <embed> tag as appropriate for the requesting client. The attributes of the jsp:plugin tag provide configuration data for the presentation of the element as well as the version of the plug-in required. The nspluginurl and iepluginurl attributes specify the URL where the plug-in can be downloaded.
The jsp:param elements specify parameters to the applet or JavaBeans component. The jsp:fallback element indicates the content to be used by the client browser if the plug-in cannot be started (either because <object> or <embed> is not supported by the client or because of some other problem).
If the plug-in can start but the applet or JavaBeans component cannot be found or started, a plug-in-specific message will be presented to the user, most likely a pop-up window reporting a ClassNotFoundException.
The Duke's Bookstore page banner.jsp that creates the banner displays a dynamic digital clock generated by DigitalClock:
The jsp:plugin element used to download the applet follows:
<jsp:plugin type="applet" code="DigitalClock.class" codebase="/bookstore2" jreversion="1.3" align="center" height="25" width="300" nspluginurl="http://java.sun.com/products/plugin/1.3.0_01 /plugin-install.html" iepluginurl="http://java.sun.com/products/plugin/1.3.0_01 /jinstall-130_01-win32.cab#Version=1,3,0,1" > <jsp:params> <jsp:param name="language" value="<%=request.getLocale().getLanguage()%>" /> <jsp:param name="country" value="<%=request.getLocale().getCountry()%>" /> <jsp:param name="bgcolor" value="FFFFFF" /> <jsp:param name="fgcolor" value="CC0066" /> </jsp:params> <jsp:fallback> <p>Unable to start plugin.</p> </jsp:fallback> </jsp:plugin>
Extending the JSP Language
You can perform a wide variety of dynamic processing tasks, including accessing databases, using enterprise services such as e-mail and directories, and flow control, with JavaBeans components in conjunction with scriptlets. One of the drawbacks of scriptlets, however, is that they tend to make JSP pages more difficult to maintain. Alternatively, JSP technology provides a mechanism, called custom tags, that allows you to encapsulate dynamic functionality in objects that are accessed through extensions to the JSP language. Custom tags bring the benefits of another level of componentization to JSP pages.
For example, recall the scriptlet used to loop through and display the contents of the Duke's Bookstore shopping cart:
<% Iterator i = cart.getItems().iterator(); while (i.hasNext()) { ShoppingCartItem item = (ShoppingCartItem)i.next(); ... %> <tr> <td align="right" bgcolor="#ffffff"> <%=item.getQuantity()%> </td> ... <% } %>An iterate custom tag eliminates the code logic and manages the scripting variable item that references elements in the shopping cart:
<logic:iterate id="item" collection="<%=cart.getItems()%>"> <tr> <td align="right" bgcolor="#ffffff"> <%=item.getQuantity()%> </td> ... </logic:iterate>Custom tags are packaged and distributed in a unit called a tag library. The syntax of custom tags is the same as that used for the JSP elements, namely <prefix:tag>, for custom tags, however, prefix is defined by the user of the tag library, and tag is defined by the tag developer. Custom Tags in JSP Pages explains how to use and develop custom tags.
Further Information
For further information on JavaServer Pages technology see:
- Resources listed on the Web site http://java.sun.com/products/jsp.
- The JavaServer Pages 1.2 Specification for a complete description of the syntax and semantics of JSTL.