Home arrow Java arrow Page 6 - JavaServer Pages, conclusion
JAVA

JavaServer Pages, conclusion


If you've taken a look at J2EE and JavaServer Pages technology, and want to examine JSP more closely, you've come to the right place. This article is the second of two parts, excerpted from chapter three of Beginning J2EE 1.4 From Novice to Professional, written by James L. Weaver, Kevin Mukhar, and Jim Crume (Apress, 2004; ISBN: 1590593413).

Author Info:
By: Apress Publishing
Rating: 4 stars4 stars4 stars4 stars4 stars / 17
November 10, 2005
TABLE OF CONTENTS:
  1. · JavaServer Pages, conclusion
  2. · The config Object
  3. · Try It Out: Using JavaBeans in JSP Pages
  4. · Translation and Compilation
  5. · The Deployment Descriptor
  6. · Including and Forwarding from JSP Pages
  7. · Summary

print this article
SEARCH DEVARTICLES

JavaServer Pages, conclusion - Including and Forwarding from JSP Pages
(Page 6 of 7 )

JSP pages have the ability to include other JSP pages or servlets in the output that is sent to a client, or to forward the request to another page or servlet for servicing. This is accomplished through the standard actions <jsp:include> and <jsp:forward>.

include Action

Including a JSP page or servlet through a standard action differs from the include directive in the time at which the other resource is included, and how the other resource is included. Recall that an include directive can be used in either of the two formats below, anywhere within the JSP:

  <%@ include file="/WEB-INF/footer.jspf"> 
  <jsp:directive.include file="/WEB-INF/footer.jspf"/>

When the JSP container translates the page, this directive causes the indicated page to be included in that place in the page, and become part of the Java source file that is compiled into the JSP page implementation class. That is, it is included at translation time. Using the include directive, the included file does not need to be a complete and valid JSP.

With the include standard action, the JSP file stops processing the current request and passes the request to the included file. The included file passes its output to the response. Then control of the response returns to the calling JSP, which finishes processing the response. The output of the included page or servlet is included at request time. Components that are included via the include action must be valid JSP pages or servlets.

The included file is not allowed to modify the headers of the response, nor to set cookies in the response.

forward Action

With the forward action, the current page stops processing the request and forwards the request to another web component. This other component completes the response. Execution never returns to the calling page. Unlike the include action, which can occur at any time during a response, the forward action must occur prior to writing any output to the OutputStream. In other words, the forward action must occur prior to any HTML template data in the JSP, and prior to any scriptlets or expressions that write data to the OutputStream. If any output has occurred in the calling JSP, an exception will be thrown when the forward action is encountered.

Using include and forward

The format of the include action is:

  <jsp:include page="URL" flush="true|false">
   
<jsp:param name="paramName" value="paramValue"/> 
  </jsp:include>

For the include element, the page attribute is required, and its value is the URL of the page whose output is included in the response. The flush attribute is optional, and indicates whether the output buffer should be flushed before the included file is called. The default value is false.

If the JSP needs to pass parameters to the included file, it does so with the <jsp:param> element. One element is used for each parameter. This element is optional. If it is included, both the name and value attributes are required. The included JSP can access the parameters using the getParameter() and getParameterValues() methods of the request object.

The format of the forward element is similar:

  <jsp:forward page="URL">
   
<jsp:param name="paramName" value="paramValue"/>
  </jsp:forward>

The meaning and use of the attributes and of the <jsp:param> element are the same as for the include action.

Try ItOut Including and Forwarding to JSP Pages

In this last example of the chapter, we will modify the JavaFAQ application to use forward actions to control the application flow. Here is the application structure:

  Ch03/
    welcome.jsp
    Dates_and_Times.jsp
    registration.jsp
    registrationform.html
    Threading.jsp
    WEB-INF/
     
footer.jspf
      errorPage.jsp
      web.xml
      BadNumber.html
      NoSuchPage.html
      formatStackTrace.jsp
      classes/
       
Ch03/
          FaqCategories.java
          FaqCategories.class
          User.java
          User.class

  1. Start by modifying welcome.jsp as shown here:

    <%@ page errorPage="/WEB-INF/errorPage.jsp" 
      import="java.util.Iterator,Ch03.*" %>
    <%
      User user = (User)session.getAttribute("user"); 
      String reqType = request.getParameter("reqType");
      if (user == null && reqType == null) {
    %>
        <jsp:forward page="registrationform.html"/>
    <%
      } else if (user == null && reqType != null) {
    %>
        <jsp:forward page="registration.jsp">
            <jsp:param name="submitTime"
                        value="<%=(new java.util.Date()).toString()%>" />
        </jsp:forward>
    <%
      }
    %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
     
    <head>
        <meta name="Cache-control" content="no-cache">
        <title>Java FAQ Welcome Page</title>
     
    </head>
     
    <body>
        <h1> Java FAQ Welcome Page</h1>
        Welcome to the Java FAQ

    <%! FaqCategories faqs = new FaqCategories(); %>
    Click a link below for answers to the given topic.
    <%
       
    Iterator categories = faqs.getAllCategories();
        while (categories.hasNext()) {
          String category = (String) categories.next();
    %>
          <p><a href="<%= replaceUnderscore(category) %>.jsp">
             <%= category %></a></p>
    <%
        }
    %>
    <%@ include file="/WEB-INF/footer.jspf" %>
      </body>
    </html>

    <%!
    public String replaceUnderscore(String s)
      {
    return s.replace(' ','_');
    }
    %>
  2. The next modified file is registrationform.html. Only the single line that contains the form tag needs to be modified as shown here:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>Registration Page</title>
      </head>
      <body>
        <h1> Registration Page</h1>
        <form action="welcome.jsp?reqType=register" method="POST">
          <table>
    <!-- The remainder of registrationform.html is the same as before, so it is not shown here >
  3. A single new line of code has been added to the registration.jsp file; only the applicable snippet is shown here:

    <%    String[] topics = request.getParameterValues("topics");
          if (topics == null) { topics = new String[] {"No topics"}; }
          for (int i = 0; i < topics.length; i++) {
    %>
            <br><%= topics[i] %>
    <%
          }
    %>
          <p>This request was submitted at
            <%= request.getParameter("submitTime") %>
          <p>Go to <a href="welcome.jsp">Topic List Page</a></p>
        <%@ include file="/WEB-INF/footer.jspf" %>
      </body>
    </html>
  4. This next file is errorPage.jsp. This file now has an include action in addition to the include directive for the standard footer:

    <%@ page isErrorPage="true" import="java.io.PrintWriter" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
       
    <title>Error</title>
      </head>
      <body>
       
    <h1> Error</h1>
        There was an error somewhere.
        <p>Here is the stack trace
       
    <p>
          <% request.setAttribute("ex", exception); %>
          <jsp:include page="formatStackTrace.jsp" />

    <%@ include file="/WEB-INF/footer.jspf" %>
      </body>
    </html>
  5. The JSP page included by the include action in errorPage.jsp is shown here. It is named formatStackTrace.jsp:

    <%@ page import="java.io.PrintWriter" %>
    <%
      out.println("<pre>");
      Throwable t = (Throwable) request.getAttribute("ex");
      if (t != null) {
       
    t.printStackTrace(new PrintWriter(out));
      }
      out.println("</pre>");
    %>
  6. Create the web application with these new files, and the files developed in previous examples. Deploy the application to the J2EE server or the Tomcat stand-alone server. For the J2EE server, use the same web application settings as in the previous Try It Out example. For Tomcat, you can use the same deployment descriptor as in the previous Try It Out example.
  7. Open a browser and enter the appropriate address for the welcome.jsp page. The browser will display the registration form page.
  8. Enter the appropriate parameters, and click the Submit button. The browser will display the registration page.
  9. Click the link in the registration page, and the browser will display the welcome page with the topic list. If the topic list is not displayed, your browser has probably cached the welcome page. Click the refresh button to get the correct page.

Click the Threading topic link. The browser will display the errorPage.jsp with a nicely formatted stack trace: 
                                      

How It Works

The first thing the welcome.jsp does now is to check for the existence of the user object, as previously, and for a request parameter with the name reqType. As before, the user object is put into the session by the registration.jsp; the reqType parameter will be added to the request by the registrationform.html page. If both of these are null, neither the registrationform.html nor registration.jsp pages has been called, so the welcome.jsp forwards the request to the registrationform.html page:

  <%
   
User user = (User)session.getAttribute("user");
   
String reqType = request.getParameter("reqType");
   
if (user == null && reqType == null) {
  %>
     
<jsp:forward page="registrationform.html"/>

If you look at the registrationform.html, you will see that the action attribute of the <form> tag has been modified to add a request parameter to the URL. When the Submit button is clicked, the form submits to welcome.jsp. This method of submitting request parameters in the URL is known as URL encoding. This time, welcome.jsp finds that the user object is still null, but that the reqType has a value. Since this indicates that the registrationform.html page has been visited, but the registration has not been submitted, welcome.jsp forwards the request to registration.jsp; it includes another request parameter with the request using the <jsp:param> element:

  <%
    } else if (user == null && reqType != null) {
  %>
      <jsp:forward page="registration.jsp">
          <jsp:param name="submitTime"
                     value="<%=(new java.util.Date
  ()).toString()%>" />
      </jsp:forward>
  <%
    }
  %>

This flow is artificially complicated, because it probably makes more sense to have registrationform.html submit directly to registration.jsp. The main reason for submitting to welcome.jsp is to provide several different examples of the use of the <jsp:forward> action. However, there is a little justification for having all requests go through the welcome.jsp page: this is a very simple example of something known as a Model 2, or Model View Controller, architecture. With a Model 2 architecture, one component acts as a controller, directing the requests to the component that is set up to handle a particular request. We will look at the Model 2 architecture in more detail in Chapter 5.

The registration.jsp page performs the same actions as in previous examples, with the addition of reading the new request parameter added by welcome.jsp, and displaying the value of that parameter. When the user clicks the link, the request is again sent to welcome.jsp. This final time, both user and reqType are not null, so welcome.jsp does not forward the request, but completes the response itself.

Clicking the Threading topic link again calls Threading.jsp, which still causes a NumberFormatException. This time, however, errorPage.jsp includes formatStackTrace.jsp. The formatStackTrace.jsp outputs the stack trace as older versions of errorPage.jsp did, but it wraps it in a <pre> tag, so that the stack trace is nicely formatted.


blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials