Creating Dynamic Content



Creating Dynamic Content

You create dynamic content by accessing Java programming language objects from within scripting elements.

1 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 Java Servlet Technology (page 367). Figure summarizes the implicit objects.

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 (page 392).

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 (page 408).

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 (page 373). This API is used extensively when implementing tag handlers (see Tag Handlers (page 439)).

request

subtype of javax.servlet.ServletRequest

The request triggering the execution of the JSP page. See Getting Information From Requests (page 378).

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 (page 393).

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 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 (page 373)) 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 (page 423). 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 (page 412).

Shared Objects

The conditions affecting concurrent access to shared objects described in Controlling Concurrent Access to Shared Resources (page 374) 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, 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 pagescope 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 JavaBeans components with application or session scope is properly synchronized.

2 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 (page 431).

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

For example, 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:


<%! 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:


<% 
    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 in Figure below:

2. Duke's Bookstore Shopping Cart
graphics/14fig02.gif
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:


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