Академический Документы
Профессиональный Документы
Культура Документы
The Web page in Figure 11-1 is a form that allows you to select a locale and displays
the date in a manner appropriate to the locale.
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 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 (page 270). 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 an enterprise bean. The advantage of using an enterprise bean is that
the helper object is no longer responsible for connecting to the database; this
job is taken over by the enterprise bean. Furthermore, because the EJB
container maintains the pool of database connections, an enterprise bean can
get a connection quicker than the helper object can. The relevant interfaces and
classes for the enterprise bean are the database.BookDBEJBHome home
interface, database.BookDBEJB remote interface, and
thedatabase.BookDBEJBImpl implementation class, which contains all the JDBC
calls to the database.
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;
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 j2eetutorial/examples/src/web/bookstore2 directory created when you unzip the
tutorial bundle (see Downloading the Examples). To build, deploy, and run the
example:
2. Start the j2ee server.
3. Start deploytool.
5. If you have not already created the bookstore database, run ant create-web-db.
10.Save BookDBJAR.
a. Select BookDBJAR.
b. Select File Save As.
c. Navigate to the directory examples/build/web/ejb.
d. Enter bookDB.jar in the File Name field.
e. Click Save EJB JAR As.
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.
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
J2EE_HOME/repository/host/web/
context_root/_0002fpageName_jsp.java
For 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
J2EE_HOME/repository/host/web/date/_0002findex_jsp.java
Both 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 the section Servlet Life Cycle:
1. If an instance of the JSP page's servlet does not exist, the container:
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 using by 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" %>
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.
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
J2EE_HOME/repository/host/web/
context_root/_0002fpageName_jsp.java
For 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
J2EE_HOME/repository/host/web/date/_0002findex_jsp.java
Both 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 the section Servlet Life Cycle:
1. If an instance of the JSP page's servlet does not exist, the container:
a. Loads the JSP page's servlet class
b. Instantiates an instance of the servlet class
c. Initializes the servlet instance by calling the jspInit method
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 using by 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" %>
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.
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.
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
Chapter 10. Table 11-2 summarizes the implicit objects.
The context for the JSP page's servlet and any Web
application javax.servlet.ServletContext components contained in the same application.
See Accessing the Web Context.
Application-Specific Objects
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 Chapter 12. 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.
Shared Objects
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,
you must 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 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 Extending the JSP
Language.
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, you must
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, you must 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" %>
Declarations
When the scripting language is the Java programming language, variables and
methods in JSP declarations become declarations in the JSP page's servlet class.
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.
<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
}
%>
Expressions
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.
For example, all the bookstore application pages include the file banner.jsp containing
the banner content with the following directive:
<%@ include file="banner.jsp" %>
Because you must 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 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"/>
Note that if any data has already been returned to a client, the jsp:forward element
will fail with an IllegalStateException.
Param Element
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 aClassNotFoundException.
The Duke's Bookstore page banner.jsp that creates the banner displays a dynamic
digital clock generated by DigitalClock (Figure 11-3).
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>;
however, for custom tags, prefix is defined by the user of the tag library and tag is
defined by the tag developer. Chapter 13 explains how to use and develop custom
tags.