Previous     Contents     Index     Next     
iPlanet Web Server, FastTrack Edition Programmer's Guide to Servlets



Chapter 2   Servlet and JSP Examples


This chapter discusses some Servlet and JSP examples in the following sections:



Examples Shipped with iPlanet Web Server 4.1

iPlanet Web Server 4.1 comes with a set of example servlets and JSP files. You can find them at the following location:

server_root/plugins/samples/servlets

This directory contains the following directories:

  • beans -- Contains example Java Bean files for JSP 0.92.

  • beans.10 -- Contains example Java Bean files for JSP 1.x.

  • bookstore -- Contains files for an online bookstore example. This example contains both servlets and JSPs.

  • jsp.092 -- Contains subdirectories that each contain an example for JSP 0.92. To use one of these examples, you must place it in a legacy directory; see "Running 0.92 JSP" for details.

  • jsp.10 -- Contains subdirectories that each contain an example for JSP 1.x.

  • make -- Contains example makefiles for servlets. These are common makefiles containing rules that are included by all other makefiles.

  • servlets -- Contains subdirectories that each contain Java source files and makefiles for servlet examples.

  • sessions -- Contains session manager directories.

    The SimpleSession directory contains code for SimpleSessionManager.java, which is the default servlet session manager, and SimpleSession.java, which defines session objects, the sessions managed by SimpleSessionManager. The source code for SimpleSessionManager and SimpleSession are provided for you to use as the starting point for defining your own session managers if desired.

    The JdbcSession directory contains JdbcSessionManager.java and JdbcSession.java, which contain support for sessions stored in a database using JDBC.

    For more information about sessions and session managers, see Appendix A "Session Managers."

  • taglibs -- Contains an example of a custom tag library, which is described in "Creating a JSP Custom Tag Library."

  • tools -- Contains the SDKTools.jar file and other utility files.



Servlet Examples

This section discusses two servlet examples as follows:

You can find additional examples in the directory server_root/plugins/samples/servlets/servlets.

These examples are simple, introductory examples. For information about using the Java Servlet API, see the documentation provided by Sun Microsystems at:

http://java.sun.com/products/servlet/index.html


A Simple Servlet Example

The following example code defines a very simple servlet. This is the SimpleServlet example in the server_root/plugins/samples/servlets/servlets/Simple1 directory.

This servlet generates an HTML page that says "This is output from SimpleServlet." as shown in Figure 2-1.



Figure 2-1    Output from SimpleServlet.class

This example defines the main servlet class as a subclass of HttpServlet and implements the doGet method. The code is shown below:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SimpleServlet extends HttpServlet
{
   public void doGet (
         HttpServletRequest request,
         HttpServletResponse response
   ) throws ServletException, IOException
   {
         PrintWriter out;
         String title = "Simple Servlet Output";

         // set content type and other response header fields first
         response.setContentType("text/html");

         // then write the data of the response
         out = response.getWriter();

         out.println("<HTML><HEAD><TITLE>");
         out.println(title);
         out.println("</TITLE></HEAD><BODY>");
         out.println("<H1>" + title + "</H1>");
         out.println("<P>This is output from SimpleServlet.");
         out.println("</BODY></HTML>");
   }
}


Example of a Servlet that Counts Visits

The following example code defines a servlet that counts visits to a web page. This is the CounterServlet example in the server_root/plugins/samples/servlets/servlets/Counter directory.

This servlet generates an HTML page that reports the number of visits for an individual user and for all users, as shown in Figure 2-2.



Figure 2-2    Output from CounterServlet.class

This example defines the main servlet class as a subclass of HttpServlet and implements the doGet method, as the SimpleServlet example did, but it also defines a thread, tracks total hits by reading from and writing to a file, and tracks hits from individual users using a cookie. The code is shown below:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CounterServlet extends HttpServlet
{   
   private File _counterFile = new File ("/tmp/CounterServlet.dat");
   private CounterWriterThread _cntWrtThread = new CounterWriterThread ();
   private int _cnt = 0;
   
   private boolean _fTerminating = false;
   
   public void init (ServletConfig config)
      throws ServletException
   {
      super.init (config);
      
      readCounter ();
      _cntWrtThread.start ();
      
   }
   
   public class CounterWriterThread
      extends Thread
   {
      public void run ()
      {
         while (!_fTerminating)
         {
            writeCounter ();
            try   {
               sleep (1000);
            }
            catch (Exception ie)
            {
            }
         }
      }
   }


   private void writeCounter ()
   {
      DataOutputStream dos = null;
      
      try   {
         dos = new DataOutputStream (new FileOutputStream (_counterFile));
         dos.writeInt (_cnt);
      }
      catch (Exception e)
      {
      }
      finally   {
         try   {
            if (dos != null)
               dos.close ();
         }
         catch (Exception ioe)
         {
         }
      }
   }
   
   private void readCounter ()
   {
      DataInputStream dis = null;
      
      try   {
         dis = new DataInputStream (new FileInputStream (_counterFile));
         _cnt = dis.readInt ();
      }
      catch (Exception e)
      {
      }
      finally   {
         try   {
            if (dis != null)
               dis.close ();
         }
         catch (Exception ioe)
         {
         }
      

   }
   
public void doGet (
HttpServletRequest request,
HttpServletResponse response
)
      throws ServletException, IOException
{
PrintWriter out;

// set content type and other response header fields first
response.setContentType("text/html");

// then write the data of the response
out = response.getWriter ();

      _cnt++;

      Cookie cookies[] = request.getCookies();
      Integer nof = new Integer (0);

      for(int i = 0; i < cookies.length; i++ )
      {
         if (cookies[i].getName ().equals ("CounterServletCookie"))
         {
            String nofS = cookies[i].getValue ();
            try   {
               nof = Integer.valueOf (nofS);
            }
            catch (Exception nfe)
            {
            }
            break;
         }
      }
      
      nof = new Integer (nof.intValue () + 1);   
      Cookie c = new Cookie ("CounterServletCookie", nof.toString ());

      c.setMaxAge (3600 * 24 * 365);
      c.setPath ("/");
      
      response.addCookie (c);
      
out.println("<HTML><BODY><CENTER>");
      
      if (nof.intValue () > 1)
         out.println ("Thank you for coming back. You have visited this page <B>"
            + nof + "</b> times");

      out.println("This page was accessed <B>" + _cnt + "</B> times total");
      out.println("</CENTER></BODY></HTML>");
   }
}



JSP Examples



This section presents the following JSP examples:

You can find additional examples in the directory server_root/plugins/samples/servlets/jsp.10.

These examples are simple, introductory examples. For information about creating JSPs, see Sun Microsystem's JavaServer Pages web page at:

http://java.sun.com/products/jsp/index.html


JSP that Accesses the Request Object

JavaServer Pages (JSPs) contain both standard HTML tags and JSP tags.

All JSP pages can implicitly access the request object, which contains information about the request that invoked the page, such as the requested URI, the query string, the content type, and so on. The request object has properties such as requestURI, queryString, and contentType.

This example displays information about the current request. It gets all its data from the request object, which is automatically passed to the JSP. This is the snoop.jsp example in the server_root/plugins/samples/servlets/jsp.10/snp directory.

Figure 2-3 shows an example of the output page generated by this JSP.



Figure 2-3    Output page generated by snoop.jsp

The source code for snoop.jsp is:

<html>
<body bgcolor="white">
<h1> Request Information </h1>
<font size="4">

<%@ page session="false" %>

JSP Request Method: <%= request.getMethod() %>
<br>
Request URI: <%= request.getRequestURI() %>
<br>
Request Protocol: <%= request.getProtocol() %>
<br>

Servlet path: <%= request.getServletPath() %>
<br>
Path info: <%= request.getPathInfo() %>
<br>
Path translated: <%= request.getPathTranslated() %>
<br>
Query string: <%= request.getQueryString() %>
<br>
Content length: <%= request.getContentLength() %>
<br>
Content type: <%= request.getContentType() %>
<br>
Server name: <%= request.getServerName() %>
<br>
Server port: <%= request.getServerPort() %>
<br>
Remote user: <%= request.getRemoteUser() %>
<br>
Remote address: <%= request.getRemoteAddr() %>
<br>
Remote host: <%= request.getRemoteHost() %>
<br>
Authorization scheme: <%= request.getAuthType() %>
<hr>
The browser you are using is <%= request.getHeader("User-Agent") %>
<hr>
</font>
</body>
</html>


JSP that Responds to a Form and Uses Java Beans

This example discusses a simple JSP that accesses data on Java beans to respond to a form. This is the example in the server_root/plugins/samples/servlets/jsp.10/checkbox directory.

This example presents a web page, check.html, that displays a form asking the user to select their favorite fruits. The action of the form is checkresult.jsp. This JSP file gets information about the fruits from a Java bean. (Note that Java beans were originally designed for use with visual tool builders, and they have some overhead that can make them slow when used to retrieve data to display in web pages.)

The discussion of this example has the following sections:


The Form

The form in the page has the following elements:

  • Four checkboxes named Apples, Grapes, Oranges, and Melons

  • A Submit button

The form's method is POST and the action is checkresult.jsp. (It also works if the form's method is GET.)

<FORM TYPE=POST ACTION=checkresult.jsp>

Figure 2-4 shows an example of the form.



Figure 2-4    This form invokes a JSP as its action


The Output Page Generated by the JSP File

The JSP file checkresult.jsp responds to the form. It uses a request and then a bean to access the parameters received from the form.

The output page generated by checkresult.jsp displays the fruits that were selected. The JSP file gets information about the fruits from Java Beans.

This JSP file demonstrates the following features:

Figure 2-5 shows an example of the output from checkresult.jsp:



Figure 2-5    A JSP page generated in response to a form submission


Accessing Input Parameters

JSP pages can extract input parameters when invoked by a URL with a query string, such as when they are invoked as a form action for a form that uses the GET method. The request.getParameterValues method retrieves an object that has attributes for each parameter in the query string.

For example, if the following URL is used to invoke a JSP:

http://my_domain.com/fruits/checkresult.jsp?Apples=on&Oranges=on

The request object has properties Apples and Oranges.


Using Externally Defined Java Beans

Some bean objects, including the request object, are always available implicitly to a JSP page. Other objects, such as user-defined objects, are not automatically available to the page, in which case you have to include a <useBean> tag to tell the page which object to use.

The JSP tag <useBean> creates an instance of an externally defined Java Bean for use within the JSP page. For example, the following code creates an instance of the Java Bean object checkbox.CheckTest, which is defined in checktest.html:

<jsp:useBean id="foo" scope="page" class="checkbox.CheckTest" />

In this case, the bean instance exists for the duration of the page.

For more information about defining Java Beans, see:

http://java.sun.com/beans/index.html


Source Code for the JSP File

Here is the source code for the JSP file checkresult.jsp:

<html>

<body bgcolor="white">
<font size=5 color="red">
<%! String[] fruits; %>
<jsp:useBean id="foo" scope="page" class="checkbox.CheckTest" />

<jsp:setProperty name="foo" property="fruit" param="fruit" />
<hr>
The checked fruits (got using request) are: <br>
<%
   fruits = request.getParameterValues("fruit");
%>
<ul>
<%
if (fruits != null) {
    for (int i = 0; i < fruits.length; i++) {
%>
<li>
<%
    out.println (fruits[i]);
    }
   } else out.println ("none selected");
%>
</ul>
<br>
<hr>

The checked fruits (got using beans) are <br>

<%
      fruits = foo.getFruit();
%>
<ul>
<%
if (!fruits[0].equals("1")) {
    for (int i = 0; i < fruits.length; i++) {
%>
<li>
<%
       out.println (fruits[i]);
    }
   } else out.println ("none selected");
%>
</ul>
</font>
</body>
</html>


Creating a JSP Custom Tag Library

iPlanet Web Server 4.1 supports custom JSP tags. This section explains how to create a custom tag library using a working example. The example includes the following directories and files under the document root directory:


/dtds/
   web-jsptaglib_1_1.dtd

/jsps/
   test-tags.jar
   test-tags.jsp

To create the test-tags.jar file, you must create a work area in which you build the tag library and its associated handler classes. This work area contains the following directories and files:


workarea/taglibs/
   ./META-INF:
      taglib.tld
   ./examples:
      ExampleTagBase.class
      ExampleTagBase.java
      FooTag.class
      FooTag.java
      FooTagExtraInfo.class
      FooTagExtraInfo.java
      LogTag.class
      LogTag.java

Both sets of example files are provided with iPlanet Web Server 4.1 in the following directory:

server_root/plugins/samples/servlets/taglibs


Step 1: Create the TLD File

You first need to write a tag library definition (TLD) file outlining the custom tags and their associated handler classes. This TLD file is an XML 1.0 file.

The TLD file must reference an associated DTD file, which has to be named web-jsptaglib_1_1.dtd. This file is available at the iPlanet Web Server website for download. You must make it accessible via a URL in the TLD file (for example http://server:port/dtds/web-jsptaglib_1_1.dtd). An incorrect URL for the DTD file or a corrupt DTD file results in failures in opening your JSPs that contain custom tags.

The tag library must be named taglib.tld and must reside under the META-INF subdirectory in the taglib.jar file you will create in step 4.

Here is an example of a taglib.tld file:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://server:port/dtds/web-jsptaglib_1_1.dtd">

<!-- a tag library descriptor -->

<taglib>
<!-- after this the default space is
"http://java.sun.com/j2ee/dtds/jsptaglibrary_1_2.dtd"
-->

<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<prefix>simple</prefix>
<urn></urn>
<info>
A simple tab library for the examples
</info>

<!-- A simple Tag -->
<!-- foo tag -->
<tag>
<name>foo</name>
<tagclass>examples.FooTag</tagclass>
<teiclass>examples.FooTagExtraInfo</teiclass>
<bodycontent>JSP</bodycontent>
<info>
Perform a server side action; uses 3 mandatory attributes
</info>

<attribute>
<name>att1</name>
<required>true</required>
</attribute>
<attribute>
<name>att2</name>
<required>true</required>
</attribute>
<attribute>
<name>att3</name>
<required>true</required>
</attribute>
</tag>

<!-- Another simple tag -->
<!-- log tag -->
<tag>
<name>log</name>
<tagclass>examples.LogTag</tagclass>
<bodycontent>TAGDEPENDENT</bodycontent>
<info>
Perform a server side action; Log the message.
</info>
<attribute>
<name>toBrowser</name>
<required>false</required>
</attribute>
</tag>

</taglib>

If you do not include the DOCTYPE in your taglib.tld file, the JSP compiler throws an exception:

Unable to open taglibrary /jsps/test-tags.jar : com.sun.xml.tree.TextNode


Step 2: Create the Tag Handler Classes

Here is the ExampleTagBase.java file:

package examples;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public abstract class ExampleTagBase implements Tag {

public void setParent(Tag parent) {
this.parent = parent;
}

public void setBodyContent(BodyContent bodyOut) {
this.bodyOut = bodyOut;
}

public void setPageContext(PageContext pageContext) {
this.pageContext = pageContext;
}

public Tag getParent() {
return this.parent;
}

public int doStartTag() throws JspException {
return SKIP_BODY;
}

public int doEndTag() throws JspException {
return EVAL_PAGE;
}


// Default implementations for BodyTag methods as well
// just in case a tag decides to implement BodyTag.
public void doInitBody() throws JspException {
}

public int doAfterBody() throws JspException {
return SKIP_BODY;
}

public void release() {
bodyOut = null;
pageContext = null;
parent = null;
}
protected BodyContent bodyOut;
protected PageContext pageContext;
protected Tag parent;
}

Here is the FooTag.java file:

package examples;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.util.Hashtable;
import java.io.Writer;
import java.io.IOException;

/**
* Example1: the simplest tag
* Collect attributes and call into some actions
*
* <foo att1="..." att2="...." att3="...." />
*/

public class FooTag
extends ExampleTagBase
implements BodyTag
{
private String atts[] = new String[3];
int i = 0;

private final void setAtt(int index, String value) {
atts[index] = value;
}

public void setAtt1(String value) {
setAtt(0, value);
}

public void setAtt2(String value) {
setAtt(1, value);
}

public void setAtt3(String value) {
setAtt(2, value);
}

/**
* Process start tag
*
* @return EVAL_BODY_INCLUDE
*/
public int doStartTag() {
return EVAL_BODY_TAG;
}
public void doInitBody() throws JspException {
pageContext.setAttribute("member", atts[i]);
i++;
}

public int doAfterBody() throws JspException {
try {
if (i == 3) {
bodyOut.writeOut(bodyOut.getEnclosingWriter());
return SKIP_BODY;
} else
pageContext.setAttribute("member", atts[i]);
i++;
return EVAL_BODY_TAG;
} catch (IOException ex) {
throw new JspException(ex.toString());
}
}
}

Here is the FooTagExtraInfo.java file:

package examples;

import javax.servlet.jsp.tagext.*;

public class FooTagExtraInfo extends TagExtraInfo {
public VariableInfo[] getVariableInfo(TagData data) {
return new VariableInfo[]
{
new VariableInfo("member",
"String",
true,
VariableInfo.NESTED)
};
}
}

Here is the LogTag.java file:

package examples;


import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

import java.io.IOException;

/**
* Log the contents of the body. Could be used to handle errors etc.
*/
public class LogTag
extends ExampleTagBase
implements BodyTag
{
boolean toBrowser = false;

public void setToBrowser(String value) {
if (value == null)
toBrowser = false;
else if (value.equalsIgnoreCase("true"))
toBrowser = true;
else
toBrowser = false;
}

public int doStartTag() {
return EVAL_BODY_TAG;
}

public int doAfterBody() throws JspException {
try {
String s = bodyOut.getString();
System.err.println(s);
if (toBrowser)
bodyOut.writeOut(bodyOut.getEnclosingWriter());
return SKIP_BODY;
} catch (IOException ex) {
throw new JspException(ex.toString());
}
}
}


Step 3: Compile the Tag Handling Classes

Change to your work directory for the java classes (for example workarea/taglibs/examples) and compile the classes, setting the appropriate classpaths. The following command must be all on one line:


/usr/java1.2/bin/javac -classpath java_home/jre/lib/rt.jar:server_root/bin/https/jar/servlets.ja r:server_root/bin/https/jar/jspengine.jar *.java


Step 4: Create the JAR File

From your work directory (for example workarea/taglibs), create a JAR file that contains your taglib.tld file and the class files. Use the following command:

jar cvf ../test-tags.jar .

You should see the following output on the screen:


adding: META-INF/ (in=0) (out=0) (stored 0%)
adding: META-INF/taglib.tld (in=1459) (out=581) (deflated 60%)
adding: examples/ (in=0) (out=0) (stored 0%)
adding: examples/domake (in=235) (out=135) (deflated 42%)
adding: examples/ExampleTagBase.java (in=1123) (out=395) (deflated 64%)
adding: examples/FooTag.java (in=1455) (out=571) (deflated 60%)
adding: examples/FooTagExtraInfo.java (in=426) (out=191) (deflated 55%)
adding: examples/LogTag.java (in=994) (out=450) (deflated 54%)
adding: examples/FooTagExtraInfo.class (in=539) (out=320) (deflated 40%)
adding: examples/ExampleTagBase.class (in=1221) (out=548) (deflated 55%)
adding: examples/FooTag.class (in=1553) (out=784) (deflated 49%)
adding: examples/LogTag.class (in=1249) (out=702) (deflated 43%)

When this is complete, you should see the test-tags.jar file in the workarea directory. Type the following command to verify this:

ls -ltr test-tags.jar

You should see something like the following output on the screen:

-rw-r--r-- 1 joe staff 7009 May 18 02:37 test-tags.jar

Copy the file to your JSP directory:

cp test-tags.jar jsp_location/jsps


Step 5: Add the JAR File to the Classpaths

Edit the jvm.classpath option in the server_root/https-server_id/config/jvm12.conf file to include the path to the custom tag library file. The following example must be all on one line in the file:

jvm.classpath=java_home/jre/lib/rt.jar:java_home/lib/tools.jar:jsp_location/jsps/test-tags.jar

In addition, make sure that your custom tag library file is added to the server classpath along with the regular Java runtime and tools.

Also make sure that the web-jsptaglib_1_1.dtd file is accessible at the URL you specified in the taglib.tld file. Failure to locate this DTD URL results in errors like this in your log files:

Unable to open taglibrary /jsps/test-tags.jar : Unable to open the tag library descriptor: Stream closed.


Step 6: Create the JSP File

This section shows an example JSP file that uses the custom tags. A custom prefix, tt, indicates which tags are handed off to the custom tag library (the foo and log tags).


<%@ page language="java" %>
<%@ taglib prefix="tt" uri="/jsps/test-tags.jar" %>

<title>Testing taglibs </title>

<h1>Testing Jsp taglibs! </h1>

<p><em><tt:foo att1="hello" att2="world" att3="tags" /></em><br>
<p><em><tt:log toBrowser="true" /> Hello Taglibs!</em><br>


Step 7: Test the Custom Tags

Type the following URL in your browser:

http://server:port/jsps/test-tags.jsp

Your browser should show the following:

Testing Jsp taglibs!

Hello Taglibs!


Previous     Contents     Index     Next     
Copyright © 2000 Sun Microsystems, Inc. Some preexisting portions Copyright © 2000 Netscape Communications Corp. All rights reserved.

Last Updated July 13, 2000