JSP Actions

 < Free Open Study > 



JSP actions are processed during the request processing phase (as opposed to directives, which are processed during the translation phase). The JSP specification defines a few standard actions that must be supported by all compliant web containers. JSP also provides a powerful framework for developing custom actions, which are included in a JSP page using the taglib directive.

The jsp:include Action

The JSP specification defines the include action for including static and dynamic resources in a JSP page. With the include directive the contents of the included resource is substituted into the JSP page at translation phase but with the include action the response of the included resource is added to the current response output stream during the request processing phase.

The include action is the same as including resources using the RequestDispatcher interface. In fact, this is how the page implementation class achieves this functionality.

The following code shows how we can use the include action:

     <jsp:include page="includedPage.jsp"/> 

This action will include the output of processing includedPage.jsp within the output of the JSP page during the request processing phase.

There are some important points to note regarding the include action and directive:

  • Changing the content of the included resource used in the include action is automatically reflected the next time the including JSP is accessed. The JSP 1.2 specification doesn't specify whether containers should detect changes made to resources included using the include directive.

  • The include directive is normally used for including both dynamic and static resources, the include action is used for including only dynamic resources.

The jsp:forward Action

The JSP specification defines the forward action to be used for forwarding the response to other web application resources. The forward action is the same as forwarding to resources using the RequestDispatcher interface.

The following code shows how to use the forward action:

     <jsp:forward page="Forwarded.html"/> 

This action will forward the request to Forwarded.html.

We can only forward to a resource if content is not committed to the response output stream from the current JSP page. If content is already committed, an IllegalStateException will be thrown. To avoid this we can set a high buffer size for the forwarding JSP page.

The jsp:param Action

The JSP param action can be used in conjunction with the include and forward actions to pass additional request parameters to the included or forwarded resource. The param tag needs to be embedded in the body of the include or forward tag.

The following code shows how we can use the param action:

     <jsp:forward page="Param2.jsp">        <jsp:param name="name" value="Meeraj"/>     </jsp:forward> 

In addition to the request parameters already available, the forwarded resource will have an extra request parameter named name, with a value of Meeraj.

A JSP Loan Calculator

We'll develop a simple JSP based loan calculator that will use most of the concepts we have covered so far. The loan calculator will provide a simple interface in which we can enter an amount, an interest rate, a loan period, and the type of interest (simple or compound). The application will then calculate and display the total amount to be paid back over the loan period.

All the JSP pages will share a common header and footer. The header will display a welcome message and the footer will display the current time. To illustrate the use of the include action and directive we'll store the contents of the header and footer in two files. We'll include the header using the include directive and the footer using the include action.

The request is sent to a JSP page when the form is submitted. Depending on the type of the interest selected by the user this JSP page will use the forward action to forward the request to JSP pages that are responsible for handling the request appropriately. We will create separate JSP pages to calculate the loan amount for simple and compound interest rates.

The two JSP pages used for calculating interests will use a combination of scriptlets, expressions, and declarations to calculate and display the interests. They will also use the errorPage attribute of the page directive to handle errors if invalid data is supplied.

Implementing the Loan Calculator

header.html is shared by all pages. The JSP pages use the include directive to include the contents of this file:

     <h1>Loan Calculator</h1> 

footer.jsp is also shared by all pages. The JSP pages use the include action to include the response of the resource, which is the current date:

     <%= new java.util.Date() %> 

index.jsp displays the form for entering the information:

     <html>       <head>         <title>Include</title>       </head>       <body style="font-family:verdana;font-size:10pt;"> 

We include the header file using the include directive:

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

The we display the form for entering the information. The request is sent to controller.jsp when the form is submitted:

           <form action="controller.jsp">             <table border="0" style="font-family:verdana;font-size:10pt;">               <tr>                 <td>Amount:</td>                 <td><input type="text" name="amount" />               </tr>               <tr>                 <td>Interest in %:</td>                 <td><input type="text" name="interest"/></td>               </tr>               <tr>                 <td>Compound:</td>                 <td><input type="radio" name="type" value="C" checked/></td>               </tr>               <tr>                 <td>Simple:</td>                 <td><input type="radio" name="type" value="S" /></td>               </tr>               <tr>                 <td>Period:</td>                 <td><input type="text" name="period"/></td>               </tr>             </table>             <input type="submit" value="Calculate"/>           </form> 

We include the footer using the include action:

         <jsp:include page="footer.jsp"/>       </body>     </html> 

controller.jsp processes the request when the form is submitted from index.jsp:

     <%       String type = request.getParameter("type");       if(type.equals("S")) {     %> 

We forward the request to simple.jsp if the value of the type request parameter is S:

     <jsp:forward page="/simple.jsp"/>     <%       } else {     %> 

We forward the request to compound.jsp if the value of the type request parameter is S:

     <jsp:forward page="/compound.jsp"/>     <%       }     %> 

compound.jsp uses scriptlets, declarations, and expressions to calculate and display the principal using compound interest. If any of the values entered by the user are less than zero an exception is thrown, and the request is forwarded to an error page defined using the page directive:

     <%@ page errorPage="error.jsp" %> 

We use the JSP declaration element to define a function for calculating compound interest:

     <%!       public double calculate(double amount, double interest, int period) { 

Throw an exception if a negative value is entered for the amount:

          if(amount <= 0) {            throw new IllegalArgumentException(                                    "Amount should be greater than 0: " + amount);          } 

Throw an exception if a negative value is entered for the interest rate:

          if(interest <= 0) {             throw new IllegalArgumentException(                                 "Interest should be greater than 0: " + interest);          } 

Throw an exception if a negative value is entered for the loan period:

          if(period <= 0) {            throw new IllegalArgumentException(                                     "Period should be greater than 0: " + period);          } 

Return the principal using compound interest:

          return amount*Math.pow(1 + interest/100, period);        }     %> 

Next, include the header file:

     <html>       <head>         <title>Include</title>       </head>       <body style="font-family:verdana;font-size:10pt;">          <%@ include file="header.html" %> 

Use JSP scriptlets to extract the request parameters:

         <%           double amount = Double.parseDouble(request.getParameter("amount"));           double interest = Double.parseDouble(                                      request.getParameter("interest"));           int period = Integer.parseInt(request.getParameter("period"));         %>         <b>Pincipal using compound interest:</b> 

Use a JSP expression to display the principal:

          <%= calculate(amount, interest, period) %>          <br/><br/> 

Finally, include the footer

          <jsp:include page="footer.jsp"/>       </body>     </html> 

simple.jsp uses scriptlets, declarations and expressions to calculate and display the principal using simple interest. Again, if any of the values entered by the user are less than zero an exception is thrown and the request is forwarded to an error JSP defined using the page directive:

     <%@ page errorPage="error.jsp" %>     <%!       public double calculate(double amount, double interest, int period) {         if(amount <= 0) {           throw new IllegalArgumentException(                                   "Amount should be greater than 0: " + amount);         }         if(interest <= 0) {           throw new IllegalArgumentException(                               "Interest should be greater than 0: " + interest);         }         if(period <= 0) {           throw new IllegalArgumentException(                                    "Period should be greater than 0: " + period);         }         return amount*(1 + period*interest/100);       }     %>     <html>       <head>         <title>Compound</title>       </head>       <body style="font-family:verdana;font-size:10pt;">         <%@ include file="header.html" %>         <%           double amount = Double.parseDouble(request.getParameter("amount"));           double interest = Double.parseDouble(                                       request.getParameter("interest"));           int period = Integer.parseInt(request.getParameter("period"));         %>         <b>Pincipal using simple interest:</b>         <%= calculate(amount, interest, period) %>         <br/><br/>         <jsp:include page="footer.jsp"/>       </body>     </html> 

error.jsp displays the error message, if an exception is thrown from the JSP pages that calculate the interest. First we define the JSP as an error page using the isErrorPage attribute of the page directive:

     <%@ page isErrorPage="true" %>     <html>       <head>         <title>Simple</title>       </head>       <body style="font-family:verdana;font-size:10pt;">         <%@ include file="header.html" %> 

We use the exception implicit object to display the error message:

           <p style="color=#FF0000"><b><%= exception.getMessage() %></b></p> 

Include the footer:

          <jsp:include page="footer.jsp"/>       </body>     </html> 

Using the Loan Calculator

You should have the following web application set up:

     %CATALINA_HOME%/                     webapps/                             jsp/                                 compound.jsp                                 controller.jsp                                 error.jsp                                 footer.jsp                                 header.html                                 index.jsp                                 simple.jsp                             WEB-INF/                                     classes/ 

Deploy the web application and restart Tomcat. Then navigate to http://localhost:8080/jsp/index.jsp:

click to expand

Enter some valid values in the form and click Calculate. If you select Compound the compound.jsp JSP page will be used to calculate the principal:

click to expand

If instead we enter a value less than zero for the amount, we will see the error JSP page that we defined:

click to expand

Using JavaBeans with JSP Pages

The JSP specification defines a powerful standard action that helps to separate presentation and content by allowing page authors to interact with JavaBean components that are stored as page, request, session and application attributes. The useBean tag along with the getProperty and setProperty tags allows JSP pages to interact with JavaBean components.

The jsp:useBean Action

The useBean action creates or finds a Java object in a specified scope. The object is also made available in the current JSP page as a scripting variable. The syntax for the useBean action is:

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

At least one of the type and class attributes must be present, and we can't specify values for both the class and bean name. The useBean JSP tag works according to the following sequence:

  • First, the container tries to find an object by the specified name in the specified scope.

  • If an object is found, a scripting variable is introduced with the name specified by the id attribute and type specified by the type attribute. If the type attribute is not specified the value of the class attribute is used. The variables value is initialized to the reference to the object that is found. The body of the tag is then ignored.

  • If the object is not found and both class and beanName are not present, an InstantiationException is thrown.

  • If the class defines a non-abstract class with public no-argument constructor an object of that class is instantiated and stored in the specified scope using the specified ID. A scripting variable is introduced with the name specified by the id attribute and type specified by the class attribute. If the value of the class attribute specifies an interface, a non-public class or a class without a public no-argument constructor, an InstantiationException is thrown. The body of useBean of the tag is then executed.

  • If the beanName attribute is used then the java.beans.Bean.instantiate() method is called, passing the value of the attribute beanName. A scripting variable is introduced with the name specified by the id attribute and type specified by the type attribute. The body useBean of the tag is then executed.

The body of the useBean tag is normally used for initializing the Java object that has just been created. For example:

     <jsp:useBean   scope="request">       <% myName = "Meeraj"; %>     </jsp:useBean> 

This creates a new string and stores it as a request attribute with the name myName. A scripting variable is also made available in the request scope via the same name and is initialized to the value Meeraj.

The jsp:getProperty Action

The getProperty action can be used in conjunction with the useBean action to get the value of the properties of the bean defined by the useBean action. For example:

     <jsp:getProperty name="myBean" property="firstName"/> 

The name attribute refers to the id attribute specified in the useBean action. The property attribute refers to the name of the bean property. In this case the bean class should have a method called getFirstName() that returns a Java primitive or object.

The jsp:setProperty Action

The setProperty action can be used in conjunction with the useBean action to set the properties of a bean. We can even get the container to populate the bean properties from the request parameters without specifying the property names. In such cases the container will match the bean property names with the request parameter names. The syntax for the setProperty action is shown below:

     <jsp:setProperty name="beanName"                      property="*" |                      property="propertyName" |                      property="propertyName" param="paramName" |                      property="propertyName" value="value" /> 

To set the value of the name property of myBean to Meeraj we would use:

    <jsp:setProperty name="myBean" property="name" value="Meeraj"/> 

To set the value of the name1 property of myBean to the value of the request parameter name2 we would use:

     <jsp:setProperty name="myBean" property="name1" param="name2"/> 

To set the value of the name property of myBean to the value of the request parameter by the same name we would use:

     <jsp:setProperty name="myBean" property="name1"/> 

Finally, to set all the properties of myBean with matching request parameters from the request parameter values we would use:

     <jsp:setProperty name="myBean" property="*"/> 

The jsp:plugin Action

The plugin action enables the JSP container to render appropriate HTML to initiate the download of the Java plugin and the execution of the specified applet or bean, depending on the browser type. The plugin standard action allows us to embed applets and beans in a browser-neutral manner as the container takes care of the user agent specific issues. For example:

     <jsp:plugin type="applet" code="MyApplet.class" codebase="/">        <jsp:params>           <jsp:param name="myParam" value="123"/>        </jsp:params>        <jsp:fallback><b>Unable to load applet</b></jsp:fallback>     </jsp:plugin> 

The params and param tag are used to define applet parameters. The fallback tag can be used to define any HTML markup that needs to be rendered upon failure to start the plugin.

Tag Libraries

Tag libraries are used to define custom actions on top of the standard actions defined by the JSP specification. Custom actions allow us to insert our own tags inside the JSP pages to instigate custom processing on the server when the page is served. Custom actions are defined in a tag library descriptor.

These custom tags can be used in JSP pages by importing them using the taglib directive. Custom action names are associated with tag handler classes in the tag library descriptor. These classes provide standard callbacks to the container by implementing one of the following interfaces:

  • javax.servlet.jsp.tagext.Tag

  • javax.servlet.jsp.tagext.IterationTag

  • javax.servlet.jsp.tagext.BodyTag

These interfaces define various methods that are called by the container on the tag handler instance when the tag is parsed. These methods represent various events like the start of the tag, start of the body, and end of the tag. By returning various enumerated constants from these methods, tag class authors can get the container to perform the following tasks:

  • Skip the body

  • Evaluate the body again

  • Skip of evaluate the rest of the page



 < Free Open Study > 



Professional Java Servlets 2.3
Professional Java Servlets 2.3
ISBN: 186100561X
EAN: 2147483647
Year: 2006
Pages: 130

Similar book on Amazon

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