What Are JavaServer Pages?

 < Day Day Up > 



JavaServer Pages, or JSPs, are a simple but powerful technology used most often to generate dynamic HTML on the server side. JSPs are a direct extension of Java servlets designed to let the developer embed Java logic directly into a requested document. A JSP document must end with the extension .jsp. The following code snippet contains a simple example of a JSP file; its output is shown in Figure 2.8.

click to expand
Figure 2.8: The output of the JSP example.

 <HTML> <BODY> <% out.println("HELLO JSP READER"); %> </BODY> </HTML> 

This document looks like any other HTML document, with some added tags containing Java code. The source code is stored in a file called hello.jsp and should be copied to the document directory of the Web application to which this JSP will be deployed. When a request is made for this document, the server recognizes the .jsp extension and realizes that special handling is required. The JSP is then passed to the JSP engine (which is just another servlet mapped to the extension .jsp) for processing.

The first time the file is requested, it is translated into a servlet and then compiled into an object that is loaded into resident memory. The generated servlet then services the request, and the output is sent back to the requesting client. On all subsequent requests, the server checks to see whether the original JSP source file has changed. If it has not changed, the server invokes the previously compiled servlet object. If the source has changed, the JSP engine re-parses the JSP source. Figure 2.9 shows these steps.

click to expand
Figure 2.9: The steps of a JSP request.

start sidebar

It's essential to remember that JSPs are just servlets created from a combination of HTML and Java source. Therefore, they have the resources and functionality of a servlet.

end sidebar

The Components of a JavaServer Page

This section discusses the components of a JSP, including directives, scripting, implicit objects, and standard actions.

JSP Directives

JSP directives are JSP elements that provide global information about a JSP page. An example is a directive that includes a list of Java classes to be imported into a JSP. The syntax of a JSP directive is:

 <%@ directive {attribute="value"} %> 

Three possible directives are currently defined by the JSP specification v1.2: page, include, and taglib. These directives are defined in the following sections.

The page Directive

The page directive defines information that will globally affect the JSP containing the directive. The syntax of a JSP page directive is:

 <%@ page {attribute="value"} %> 

Table 2.2 defines the attributes for the page directive.

Table 2.2: Attributes for the page Directive

Attribute

Definition

language="scriptingLanguage"

Tells the server which language will be used to compile the JSP file. Java is currently the only available JSP language, but we hope there will be other language support in the not-too-distant future.

extends="className"

Defines the parent class from which the JSP will extend. While you can extend JSP from other servlets, doing so limits the optimizations performed by the JSP/servlet engine and is therefore not recommended.

import="importList"

Defines the list of Java packages that will be imported into this JSP. It will be a comma-separated list of package names and fully qualified Java classes.

session="true | false"

Determines whether the session data will be available to this page. The default is true. If your JSP is not planning on using the session, then this attribute should be set to false for better performance.

buffer="none | size in kb"

Determines whether the output stream is buffered. The default value is 8KB.

autoFlush="true | false"

Determines whether the output buffer will be flushed automatically, or whether it will throw an exception when the buffer is full. The default is true.

isThreadSafe="true | false"

Tells the JSP engine that this page can service multiple requests at one time. By default, this value is true. If this attribute is set to false, the SingleThreadModel is used.

info="text"

Represents information about the JSP page that can be accessed by invoking the page's Servlet.getServletInfo() method.

errorPage="error_url"

Represents the relative URL to a JSP that will handle JSP exceptions.

isErrorPage="true | false"

States whether the JSP is an errorPage. The default is false.

contentType="ctinfo"

Represents the MIME type and character set of the response sent to the client.

start sidebar

Because all mandatory attributes are defaulted, you are not required to specify any page directives.

end sidebar

The following code snippet includes a page directive that imports the java.util package:

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

The include Directive

The include directive is used to insert text and/or code at JSP translation time. The syntax of the include directive is shown in the following code snippet:

 <%@ include file="relativeURLspec" %> 

The file attribute can reference a normal text HTML file or a JSP file, which is evaluated at translation time. This resource referenced by the file attribute must be local to the Web application that contains the include directive. Here's a sample include directive:

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

start sidebar

Because the include directive is evaluated at translation time, this included text is evaluated only once. Thus, if the included resource changes, these changes are not reflected until the JSP/servlet container is restarted or the modification date of the JSP that includes that file is changed.

end sidebar

The taglib Directive

The taglib directive states that the including page uses a custom tag library, uniquely identified by a URI and associated with a prefix that distinguishes each set of custom tags to be used in the page.

start sidebar

If you are not familiar with JSP custom tags, you can learn what they are and how they are used in my book Mastering JSP Custom Tags and Tag Libraries, published by Wiley.

end sidebar

The syntax of the taglib directive is as follows:

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

The taglib attributes are described in Table 2.3.

Table 2.3: Attributes for the taglib Directive

Attribute

Definition

uri

A URI that uniquely names a custom tag library

prefix

The prefix string used to distinguish a custom tag instance

The following code snippet includes an example of how the taglib directive is used:

 <%@ taglib   uri="http://jakarta.apache.org/taglibs/random-1.0"   prefix="rand" %> 

JSP Scripting

Scripting is a JSP mechanism for directly embedding Java code fragments into an HTML page. Three scripting language components are involved in JSP scripting. Each component has its appropriate location in the generated servlet. This section examines these components.

Declarations

JSP declarations are used to define Java variables and methods in a JSP. A JSP declaration must be a complete declarative statement.

JSP declarations are initialized when the JSP page is first loaded. After the declarations have been initialized, they are available to other declarations, expressions, and scriptlets within the same JSP. The syntax for a JSP declaration is as follows:

 <%! declaration %> 

A sample variable declaration using this syntax is shown here:

 <%! String name = new String("BOB"); %> 

Here's a sample method declaration using the same syntax:

 <%! public String getName() { return name; } %> 

To get a better understanding of declarations, let's take the previous string declaration and embed it into a JSP document. The sample document would look similar to the following code snippet:

 <HTML> <BODY> <%! String name = new String("BOB"); %> </BODY> </HTML> 

When this document is initially loaded, the JSP code is converted to servlet code and the name declaration is placed in the declaration section of the generated servlet. It is now available to all other JSP components in the JSP.

start sidebar

It should be noted that all JSP declarations are defined at the class level, in the servlet generated from the JSP, and are therefore evaluated prior to all JSP expressions and scriptlet code.

end sidebar

Expressions

JSP expressions are JSP components whose text, upon evaluation by the container, is replaced with the resulting value of the container evaluation. JSP expressions are evaluated at request time, and the result is inserted at the expression's referenced position in the JSP file. If the resulting expression cannot be converted to a string, then a translation-time error occurs. If the conversion to a string cannot be detected during translation, a ClassCastException is thrown at request time.

The syntax of a JSP expression is as follows:

 <%= expression %> 

A code snippet containing a JSP expression is shown here:

 Hello <B><%= getName() %></B> 

Here is a sample JSP document containing a JSP expression:

 <HTML> <BODY> <%! public String getName() { return "Bob"; } %> Hello <B><%= getName() %></B> </BODY> </HTML> 

Scriptlets

Scriptlets are the JSP components that bring all the JSP elements together. They can contain almost any coding statements that are valid for the language referenced in the language directive. They are executed at request time, and they can make use of all the JSP components. The syntax for a scriptlet is as follows:

 <% scriptlet source %> 

When JSP scriptlet code is converted into servlet code, it is placed into the generated servlet's service() method. The following code snippet contains a simple JSP that uses a scripting element to print the text "Hello Bob" to the requesting client:

 <HTML> <BODY> <% out.println("Hello Bob"); %> </BODY> </HTML> 

You should note that while JSP scriplet code can be very powerful, composing all your JSP logic using scriptlet code can make your application difficult to manage. This problem led to the creation of custom tag libraries.

JSP Error Handling

Like all development methods, JSPs need a robust mechanism for handling errors. The JSP architecture provides an error-handling solution through the use of JSPs that are written exclusively to handle JSP errors.

The errors that occur most frequently are runtime errors that can arise either in the body of the JSP page or in some other object that is called from the body of the JSP page. Request-time errors that result in an exception being thrown can be caught and handled in the body of the calling JSP, which signals the end of the error. Exceptions that are not handled in the calling JSP result in the forwarding of the client request, including the uncaught exception, to an error page specified by the offending JSP.

Creating a JSP Error Page

Creating a JSP error page is a simple process: you create a basic JSP and then tell the JSP engine that the page is an error page. You do so by setting the JSP's page directive attribute, isErrorPage, to true. Listing 2.6 contains a sample error page.

Listing 2.6: Creating a JSP error page: errorpage.jsp.

start example
 <html> <%@ page isErrorPage="true" %> Error: <%= exception.getMessage() %> has been reported. </body> </html> 
end example

The first JSP-related line in this page tells the JSP compiler that this JSP is an error page. This code snippet is:

 <%@ page isErrorPage="true" %> 

The second JSP-related section uses the implicit exception object that is part of all JSP error pages to output the error message contained in the unhandled exception that was thrown in the offending JSP.

Using a JSP Error Page

To see how an error page works, let's create a simple JSP that throws an uncaught exception. The JSP shown in Listing 2.7 uses the error page created in the previous section.

Listing 2.7: Using a JSP error page: testerror.jsp.

start example
 <%@ page errorPage="errorpage.jsp" %> <%   if ( true ) {     // Just throw an exception     throw new Exception("An uncaught Exception");   } %> 
end example

Notice in this listing that the first line of code sets errorPage equal to errorpage.jsp, which is the name of the error page. To make a JSP aware of an error page, you simply need to add the errorPage attribute to the page directive and set its value equal to the location of your JSP error page. The rest of the example simply throws an exception that will not be caught. To see this example in action, copy both JSPs to the <CATALINA_HOME>/webapps/ch02app/ directory and open the testerror.jsp page in your browser. You will see a page similar to Figure 2.10.

click to expand
Figure 2.10: The output of the testerror.jsp example.

Implicit Objects

As a JSP author, you have implicit access to certain objects that are available for use in all JSP documents. These objects are parsed by the JSP engine and inserted into the generated servlet as if you defined them yourself.

out

The implicit out object represents a JspWriter (derived from a java.io.Writer) that provides a stream back to the requesting client. The most common method of this object is out.println(), which prints text that will be displayed in the client's browser. Listing 2.8 provides an example using the implicit out object.

Listing 2.8: Using the out object: out.jsp.

start example
 <%@ page errorPage="errorpage.jsp" %> <html>   <head>     <title>Use Out</title>   </head>   <body>     <%       // Print a simple message using the implicit out object.       out.println("<center><b>Hello WROX" +         " Reader!</b></center>");     %>   </body> </html> 
end example

To execute this example, copy this file to the <CATALINA_HOME>/webapps/ch02app/ directory and then open your browser to the following URL:

  • http://localhost:8080/ch02app/out.jsp

You should see a page similar to Figure 2.11.

click to expand
Figure 2.11: The output of out.jsp.

request

The implicit request object represents the javax.servlet.http.HttpServletRequest interface, discussed later in this chapter. The request object is associated with every HTTP request.

One of the more common uses for the request object is to access request parameters. You can do this by calling the request object's getParameter() method with the parameter name you are seeking. It returns a string with the value matching the named parameter. An example using the implicit request object appears in Listing 2.9.

Listing 2.9: Using the request object: request.jsp.

start example
 <%@ page errorPage="errorpage.jsp"  %> <html>   <head>     <title>UseRequest</title>   </head>   <body>     <%       out.println("<b>Welcome: " +         request.getParameter("user") + ''</b>");     %>   </body> </html> 
end example

This JSP calls the request.getParameter() method, passing it the parameter user. This method looks for the key user in the parameter list and returns the value, if it is found. Enter the following URL in your browser to see the results from this page:

  • http://localhost:8080/ch02app/request.jsp?user=Robert

After loading this URL, you should see a page similar to Figure 2.12.

click to expand
Figure 2.12: The output of request.jsp.

response

The implicit response object represents the javax.servlet.http.HttpServletResponse object. The response object is used to pass data back to the requesting client. This implicit object provides all the functionality of the HttpServletRequest, just as if you were executing in a servlet. One of the more common uses for the response object is writing HTML output back to the client browser; however, the JSP API already provides access to a stream back to the client using the implicit out object, as described earlier.

pageContext

The pageContext object provides access to the namespaces associated with a JSP page. It also provides accessors to several other JSP implicit objects. A common use for the pageContext is setting and retrieving objects using the setAttribute() and getAttribute() methods.

session

The implicit session object represents the javax.servlet.http.HttpSession object. It's used to store objects between client requests, thus providing an almost stateful HTTP interactivity.

An example of using the session object is shown in Listing 2.10.

Listing 2.10: Using the session object: session.jsp.

start example
 <%@ page errorPage="errorpage.jsp" %> <html>   <head>     <title>Session Example</title>   </head>   <body>     <%       // get a reference to the current count from the session       Integer count = (Integer)session.getAttribute("COUNT");       if ( count == null ) {         // If the count was not found create one         count = new Integer(1);         // and add it to the HttpSession         session.setAttribute("COUNT", count);       }       else {         // Otherwise increment the value         count = new Integer(count.intValue() + 1);         session.setAttribute("COUNT", count);       }       out.println("<b>You have accessed this page: "         + count + " times.</b>");     %>   </body> </html> 
end example

To use this example, copy the JSP to the <CATALINA_HOME>/ch02app/ directory and open your browser to the following URL:

  • http://localhost:8080/ch02app/session.jsp

Click the Refresh button a few times to see the count increment.

If everything went okay, you should see a page similar to Figure 2.13.

click to expand
Figure 2.13: The output of session.jsp.

application

The application object represents the javax.servlet.ServletContext, discussed earlier in this chapter. The application object is most often used to access objects stored in the ServletContext to be shared between Web components in a global scope. It is a great place to share objects between JSPs and servlets. An example using the application object can be found earlier in this chapter, in the section "The ServletContext."

config

The implicit config object holds a reference to the ServletConfig, which contains configuration information about the JSP/servlet engine containing the Web application where this JSP resides.

page

The page object contains a reference to the current instance of the JSP being accessed. The page object is used just like this object, to reference the current instance of the generated servlet representing this JSP.

exception

The implicit exception object provides access to an uncaught exception thrown by a JSP. It is available only in JSPs that have a page with the attribute isErrorPage set to true.

Standard Actions

JSP standard actions are predefined custom tags that can be used to encapsulate common actions easily. There are two types of JSP standard actions: the first type is related to JavaBean functionality, and the second type consists of all other standard actions. We define and use each group in the following sections.

Three predefined standard actions relate to using JavaBeans in a JSP: <useBean>, <setProperty>, and <getProperty>. After we define these tags, we create a simple example that uses them.

<jsp:useBean>

The <jsp:useBean> JavaBean standard action creates or looks up an instance of a JavaBean with a given ID and scope. Table 2.4 contains the attributes of the <jsp:useBean> action, and Table 2.5 defines the scope values for that action. The <jsp:useBean> action is very flexible. When a <useBean> action is encountered, the action tries to find an existing object using the same ID and scope. If it cannot find an existing instance, it attempts to create the object and store it in the named scope associated with the given ID. The syntax of the <jsp:useBean> action is as follows:

 <jsp:useBean          scope="page|request|session|application"         typeSpec>         body </jsp:useBean> typeSpec ::= |          type="typeName" |         type="typeName"  |         beanName="beanName" type="typeName" |         type="typeName" beanName="beanName" |         type="typeName" 

Table 2.4: Attributes for the <jsp:useBean> Standard Action

Attribute

Definition

id

The key associated with the instance of the object in the specified scope. This key is case sensitive. The id attribute is the same key as used in the page.getAttribute() method.

scope

The life of the referenced object. The scope options are page, request, session, and application. They are defined in Table 2.5.

class

The fully qualified class name that defines the implementation of the object. The class name is case sensitive.

beanName

The name of the JavaBean.

type

The type of scripting variable defined. If this attribute is unspecified, then the value is the same as the value of the class attribute.

Table 2.5: Scope Values for the <jsp:useBean> Standard Action

Value

Definition

page

Beans with page scope are accessible only within the page where they were created. References to an object with page scope will be released when the current JSP has completed its evaluation.

request

Beans with request scope are accessible only within pages servicing the same request in which the object was instantiated, including forwarded requests. All references to the object are released once the request is complete.

session

Beans with session scope are accessible only within pages processing requests that are in the same session as the one in which the bean was created. All references to beans with session scope are released once their associated session expires.

application

Beans with application scope are accessible within pages processing requests that are in the same Web application. All references to beans are released when the JSP/servlet container is shut down.

The scope attribute listed in Table 2.4 can have four possible values, which are described in Table 2.5.

<jsp:setProperty>

The <jsp:setProperty> standard action sets the value of a bean's property. Its name attribute represents an object that must already be defined and in scope. The syntax for the <jsp:setProperty> action is as follows:

 <jsp:setProperty name="beanName" propexpr /> 

In the preceding syntax, the name attribute represents the name of the bean whose property you are setting, and propexpr can be represented by any of the following expressions:

 property="*" | property="propertyName" | property="propertyName" param="parameterName" | property="propertyName" value="propertyValue" 

Table 2.6 contains the attributes and their descriptions for the <jsp:setProperty> action.

Table 2.6: Attributes for the <jsp:setProperty> Standard Action

Attribute

Definition

name

The name of the bean instance defined by a <jsp:useBean> action or some other action.

property

The bean property for which you want to set a value. If you set propertyName to an asterisk (*), then the action will iterate over the current ServletRequest parameters, matching parameter names and value types to property names and setter method types and setting each matched property to the value of the matching parameter. If a parameter has an empty string for a value, the corresponding property is left unmodified.

param

The name of the request parameter whose value you want to set the named property to. A <jsp:setProperty> action cannot have both param and value attributes referenced in the same action.

value

The value assigned to the named bean's property.

<jsp:getProperty>

The last standard action that relates to integrating JavaBeans into JSPs is <jsp:getProperty>. It takes the value of the referenced bean's instance property, converts it to a java.lang.String, and places it on the output stream. The referenced bean instance must be defined and in scope before this action can be used. The syntax for the <jsp:getProperty> action is as follows:

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

Table 2.7 contains the attributes and their descriptions for the <jsp:getProperty> action.

Table 2.7: Attributes for the <jsp:getProperty> Standard Action

Attribute

Definition

name

The name of the bean instance from which the property is obtained, defined by a <jsp:useBean> action or some other action.

property

The bean property for which you want to get a value.

A JavaBean Standard Action Example

To learn how to use the JavaBean standard actions, let's create an example. This example uses a simple JavaBean that acts as a counter. The Counter bean has a single int property, count, that holds the current number of times the bean's property has been accessed. It also contains the appropriate methods for getting and setting this property. Listing 2.11 contains the source code for the Counter bean.

Listing 2.11: Example of a Counter bean: Counter.java.

start example
 package chapter2; public class Counter {   int count = 0;   public Counter() {   }   public int getCount() {     count++;     return count;   }   public void setCount(int count) {     this.count = count;   } } 
end example

Let's look at integrating this sample JavaBean into a JSP, using the JavaBean standard actions. Listing 2.12 contains the JSP that leverages the Counter bean.

Listing 2.12: A JSP that uses the Counter bean: counter.jsp.

start example
 <!-- Set the scripting language to java --> <%@ page language="java" %> <HTML> <HEAD> <TITLE>Bean Example</TITLE> </HEAD> <BODY> <!-- Instantiate the Counter bean with an id of "counter" --> <jsp:useBean  scope="session"    /> <%   // write the current value of the property count   out.println("Count from scriptlet code : "     + counter.getCount() + "<BR>"); %> <!-- Get the the bean's count property, --> <!-- using the jsp:getProperty action. --> Count from jsp:getProperty :   <jsp:getProperty name="counter" property="count" /><BR> </BODY> </HTML> 
end example

Counter.jsp has four JSP components. The first component tells the JSP container that the scripting language is Java:

 <%@ page language="java" %> 

The next step uses the standard action <jsp:useBean> to create an instance of the class Counter with a scope of session and ID of counter. Now you can reference this bean using the name counter throughout the rest of the JSP. The code snippet that creates the bean is as follows:

 <jsp:useBean  scope="session"    /> 

The final two actions demonstrate how to get the current value of a bean's property. The first of these two actions uses a scriptlet to access the bean's property, using an explicit method call. It simply accesses the bean by its ID, counter, and calls the getCount() method. The scriptlet snippet is listed here:

 <%    // write the current value of the property count    out.println("Count from scriptlet code : "      + counter.getCount() + "<BR>"); %> 

The second example uses the <jsp:getProperty> standard action, which requires the ID of the bean and the property to be accessed. The action takes the attribute, calls the appropriate accessor, and embeds the results directly into the resulting HTML document, as follows:

 <!-- Get the bean's count property, --> <!-- using the jsp:getProperty action. --> Count from jsp:getProperty :   <jsp:getProperty name="counter" property="count" /><BR> 

When you execute the Counter.jsp, notice that the second reference to the count property results in a value that is one greater than the first reference. This is the case because both methods of accessing the count property result in a call to the getCount() method, which increments the value of count.

To see this JSP in action, compile the Counter class, move it to the <CATALINA_HOME>/ch02app/WEB-INF/classes/chapter2/ directory, and copy the Counter.jsp file to the <CATALINA_HOME>/ch02app/ directory. Then, open your browser to the following URL:

  • http://localhost:8080/ch02app/counter.jsp

Once the JSP is loaded, you should see an image similar to Figure 2.14.

click to expand
Figure 2.14: The results of counter.jsp.

The remaining standard actions are used for generic tasks, from basic parameter action to an object plug-in action. These actions are described in the following sections.

<jsp:param>

The <jsp:param> action provides parameters and values to the JSP standard actions <jsp:include>, <jsp:forward>, and <jsp:plugin>. The syntax of the <jsp:param> action is as follows:

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

Table 2.8 contains the attributes and their descriptions for the <jsp:param> action.

Table 2.8: Attributes for the <jsp:param> Action

Attribute

Definition

name

The name of the parameter being referenced

value

The value of the named parameter

<jsp:include>

The <jsp:include> standard action provides a method for including additional static and dynamic Web components in a JSP. The syntax for this action is as follows:

 <jsp:include page="urlSpec" flush="true">     <jsp:param ... /> </jsp:include> 

Table 2.9 contains the attributes and their descriptions for the <jsp:include> action.

Table 2.9: Attributes for the <jsp:include> Action

Attribute

Definition

page

The relative URL of the resource to be included

Flush

A mandatory Boolean value stating whether the buffer should be flushed

start sidebar

It is important to note the difference between the include directive and the include standard action. The directive is evaluated only once, at translation time, whereas the standard action is evaluated with every request.

end sidebar

The syntax description shows a request-time inclusion of a URL that is passed an optional list of param subelements used to argument the request. You can see an example using the include standard action in Listing 2.13.

Listing 2.13: Example of the include action: include.jsp.

start example
 <html>   <head>     <title>Include Example</title>   </head>   <body>     <table width="100%" cellspacing="0">       <tr>         <td align="left">           <jsp:include page="header.jsp" flush="true">             <jsp:param name="user"               value='<%= request.getParameter("user") %>' />           </jsp:include>         </td>       </tr>     </table>   </body> </html> 
end example

This file contains a single include action that includes the results of evaluating the JSP header.jsp, shown in Listing 2.14.

Listing 2.14: The JSP evaluated in include.jsp: header.jsp.

start example
 <%   out.println("<b>Welcome: </b>" +     request.getParameter("user")); %> 
end example

This JSP simply looks for a parameter named user and outputs a string containing a welcome message. To deploy this example, copy these two JSPs to the <CATALINA_HOME>/webapps/ch02app/ directory. Open your browser to the following URL:

  • http://localhost:8080/ch02app/include.jsp?user=Bob

The results should look similar to Figure 2.15.

click to expand
Figure 2.15: The results of include.jsp.

<jsp:forward>

The <jsp:forward> standard action enables the JSP engine to execute a runtime dispatch of the current request to another resource existing in the current Web application, including static resources, servlets, or JSPs. The appearance of <jsp:forward> effectively terminates the execution of the current JSP.

start sidebar

A <jsp:forward> action can contain <jsp:param> subattributes. These subattributes act as parameters that are forwarded to the targeted resource.

end sidebar

The syntax of the <jsp:forward> action is as follows:

 <jsp:forward page="relativeURL">     <jsp:param .../> </jsp:forward> 

Table 2.10 contains the attribute and its description for the <jsp:forward> action.

Table 2.10: Attribute for the <jsp:forward> Action

Attribute

Definition

page

The relative URL of the target of the forward

The example in Listing 2.15 contains a JSP that uses the <jsp:forward> action. This example checks a request parameter and forwards the request to one of two JSPs based on the value of the parameter.

Listing 2.15: Example of the forward action: forward.jsp.

start example
 <html>   <head>     <title>JSP Forward Example</title>   </head>   <body>     <%       if ( (request.getParameter("role")).equals("manager") ) {         %>           <jsp:forward page="management.jsp" />         <%       }       else {         %>           <jsp:forward page="welcome.jsp">           <jsp:param name="user"             value='<%=request.getParameter("user") %>' />           </jsp:forward>         <%       }     %>   </body> </html> 
end example

The forward.jsp simply checks the request for the parameter role and forwards the request, along with a set of request parameters, to the appropriate JSP based on this value. Listings 2.16 and 2.17 contain the source of the targeted resources.

Listing 2.16: welcome.jsp.

start example
 <html> <!-- Set the scripting language to java --> <%@ page language="java" %> <HTML> <HEAD> <TITLE>Welcome Home</TITLE> </HEAD> <BODY> <table>   <tr>     <td>       Welcome User: <%= request.getParameter("user") %>     </td>   </tr> </table> 
end example

Listing 2.17: management.jsp.

start example
 <html> <!-- Set the scripting language to java --> <%@ page language="java" %> <HTML> <HEAD> <TITLE>Management Console</TITLE> </HEAD> <BODY> <table>   <tr>     <td>       Welcome Manager: <%= request.getParameter("user") %>     </td>   </tr> </table> 
end example

To test this example, copy all three JSPs to the <CATALINA_HOME>/webapps/ch02app/ directory and open your browser to the following URL:

  • http://localhost:8080/ch02app/forward.jsp?role=user&user=Bob

You will see an image similar to Figure 2.16.

click to expand
Figure 2.16: The output of forward.jsp.

You can also change the value of the role parameter to manager, to change the forwarded target.

<jsp:plugin>

The last standard action we discuss is <jsp:plugin>. This action enables a JSP author to generate the required HTML, using the appropriate client-browser independent constructs, to result in the download and subsequent execution of the specified applet or JavaBeans component.

The <jsp:plugin> tag, once evaluated, is replaced by either an <object> or <embed> tag, as appropriate for the requesting user agent. The attributes of the <jsp:plugin> action provide configuration data for the presentation of the embedded element. The syntax of the <jsp:plugin> action is as follows:

 <jsp:plugin type="pluginType"     code="classFile"     codebase="relativeURLpath">     <jsp:params>     </jsp:params> </jsp:plugin> 

Table 2.11 contains the attributes and their descriptions for the <jsp:plugin> action.

Table 2.11: Attributes for the <jsp:plugin> Action

Attribute

Definition

type

The type of plug-in to include (an applet, for example)

code

The name of the class that will be executed by the plug-in

codebase

The base or relative path where the code attribute can be found

The <jsp:plugin> action also supports the use of the <jsp:params> tag to supply the plug-in with parameters, if necessary.



 < Day Day Up > 



Professional Jakarta Struts
Professional Jakarta Struts (Programmer to Programmer)
ISBN: 0764544373
EAN: 2147483647
Year: 2003
Pages: 183

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net