Home arrow Java arrow Page 4 - JavaServer Pages
JAVA

JavaServer Pages


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, the first of two parts, is 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 / 10
November 03, 2005
TABLE OF CONTENTS:
  1. · JavaServer Pages
  2. · Writing JSP Pages
  3. · Scriptlets
  4. · Template Data
  5. · Try It Out: Deploying the Web Application in J2EE
  6. · Try It Out: Deploying the Web Application in Tomcat
  7. · Action Elements

print this article
SEARCH DEVARTICLES

JavaServer Pages - Template Data
(Page 4 of 7 )

Everything that is not a directive, declaration, scriptlet, expression, or JSP comment (usually all the HTML and text in the page) is termed template data. This data is output to the client as if it had appeared within a static web page.

Try It Out Creating a JSP Web Application

OK, now we really will develop an example JSP page using the information seen so far. This page will provide a welcome page to an application that manages a Frequently Asked Questions (FAQ) forum. Once weve written the code, we will use this example to show how to deploy a JSP application to the J2EE reference implementation server and to a stand-alone Tomcat server.

  1. Start by creating a directory structure to match the web application. If you are planning to deploy this application to Tomcat stand-alone, you can create this directory directly in the Tomcat /webapps directory. Here is the directory structure, with the files that will be created:

      Ch03/
        welcome.jsp
        WEB-INF/
          web.xml
          footer.jspf
          errorPage.jsp
          classes/
            Ch03/
              FaqCategories.java
              FaqCategories.class


    As you go through the following steps and create each file, refer to the directory structure above to determine where to save each file.
  2. Lets start with the page that welcomes users to the web application. This is the welcome.jsp file:

    <%@ page errorPage="/WEB-INF/errorPage.jsp"  
            import="java.util.Iterator,Ch03.FaqCategories" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <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(' ','_');
    }
    %>

  3. The welcome.jsp page above has a JSP include directive to add a standard footer. Because the include file is just a fragment and not a complete JSP file, we use the convention of naming the file with a .jspf extension as recommended by the JSP specification. Here is the footer.jspf file:

    <hr>
    Page generated on <%= (new java.util.Date()).toString() %>

  4. Now create errorPage.jsp:

    <%@ 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.
        <%@ include file="/WEB-INF/footer.jspf" %>
     
    </body>
    </html>

  5. And finally, we have a helper file that will be used by welcome.jsp. This file is FaqCategories.java. After entering the source, compile the file into a class file.

    package Ch03;
    import java.util.Iterator;
    import java.util.Vector;
    public class FaqCategories {
      private Vector categories = new Vector();
     
    public FaqCategories() {
        categories.add("Dates and Times");
        categories.add("Strings and StringBuffers"); 
        categories.add("Threading");
     
    }
      public Iterator getAllCategories() {
        return categories.iterator();
      }
    }
How It Works

The welcome.jsp file demonstrates many of the features that have been introduced in this chapter so far. It begins with the page directive. This directive has two attributes, as shown below. First, an errorPage is defined, to which the browser will be redirected if an error occurs on the page. The other attribute used with the page directive is the import. The page imports two Java classes: the Iterator class from the Java API and the FaqCategories class that is part of this application:

  <%@ page errorPage="/WEB-INF/errorPage.jsp" 
           import="java.util.Iterator,Ch03.FaqCategories" 
  %>

Note that the page can also use this syntax for the import:

  <%@ page errorPage="/WEB-INF/errorPage.jsp" 
           import="java.util.*,Ch03.*" %>

This is followed by some straight HTML. Further down in the page is a declaration scripting element. This element declares a variable called faqs and initializes it by calling the constructor of the FaqCategories helper class. You can see that declaration elements must follow Java coding rules, including the use of a semicolon to terminate the statement:

  <%! FaqCategories faqs = new FaqCategories(); %>

The next JSP element in the page is a scriptlet. This scriptlet gets an Iterator from the FaqCategories instance. We use this Iterator to loop through each of the categories defined in the FaqCategories class. Each category is loaded into a String variable called category, and this is used to create an HTML link. Each category is printed out twice using expression elementsfirst within the href attribute of the <a> tag to set the page that the link refers to, and then within the body of the link. The first expression element calls the replaceUnderscore() method (defined later in the page) and prints the result; the other expression element simply prints the category value:

  <%
   
Iterator categories = faqs.getAllCategories();
   
while (categories.hasNext()) {
   
String category = (String)categories.next();
 
%>
      <p><a href="/<%= replaceUnderscore(category) %>"><%
  = category %></a></p>
  <%
    }
  %>

Notice that with the scriptlet, Java syntax must be used. However, within an expression element, you only need to use the expression itself, without a semicolon to end the statement.

At the bottom of the page, an include directive includes a standard footer:

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

The last thing in the file is another declaration element. This element, shown below, declares the replaceUnderscore() method, which replaces the spaces in a string with underscores. It was called by the scriptlet earlier in the file:

  <%!
  public String replaceUnderscore(String s) {
   
return s.replace(' ','_');
  }
  %>

The next file is footer.jspf:

  <hr>
  Page generated on <%= (new java.util.Date()).toString() %
  >

You will see that this is not a complete JSP file. This file uses an expression element to print out the current date and time at the server when the page is served to the user. I used the extension .jspf as recommended by the specification to indicate that this file is a fragment. Also, because it is a fragment and is not meant to be publicly available, the file was put into the WEB-INF directory. Files in this directory are not publicly available. This means that you cannot enter an address into a browser to access this file. Only code within the application can access files within the WEB-INF directory.

The errorPage.jsp is meant to be used when an uncaught exception occurs in the welcome.jsp page. It includes the standard footer. However, assuming everything in the page is correct, it will not be called in this application. This page is not meant to be publicly available, so it too resides in the WEB-INF directory:

  <%@ 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.
     
<%@ include file="/WEB-INF/footer.jspf" %>
   
</body>
  </html>

Since this is an error page, notice that we set the isErrorPage attribute of the page directive to true. Apart from that directive, this page contains just straight HTML and an include directive to include our footer.jspf file.

The final source file is FaqCategories.java. This is a helper class that supplies three categories to the welcome.jsp page. In a real-world application, the categories would come from some persistent store such as a database or a directory. For this example, we use the helper class to hard-code the categories for welcome.jsp:

  package Ch03;
 
import java.util.Iterator;
  import java.util.Vector;
 
public class FaqCategories {
    private Vector categories = new Vector();
   
public FaqCategories() {
      categories.add("Dates and Times");
      categories.add("Strings and StringBuffers");
      categories.add("Threading");
   
}
    public Iterator getAllCategories() {
      return categories.iterator();
    }
  }

The categories are stored in a Vector object, which is an instance member of the class. In the class constructor, we just add our hard-coded categories to this Vector. Finally, we define a getAllCategories() method, which simply returns the Iterator for our Vector. Our JSP page uses this Iterator to loop through each of the categories in turn.


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