Table of Contents | Previous | Next | Index | Bookshelf

Programmer's Guide to Servlets


Chapter 2. Servlet and JSP Examples

This chapter discusses some Servlet and JSP examples. It has 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:

The SimpleSession directory contains code for SimpleSessionManager.java, which is the default servlet session manager when the iPlanet Web Server runs in single process mode, 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."

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:

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>


Table of Contents | Previous | Next | Index

Last Updated: 02/25/00 16:19:10

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