Servlets

Date: 4/29/2002

Some Basic Web Concepts

In the early days of web, it was realized that it was necessary to be able to collect information from the user, then use that information in some way.

The information would be collect using an HTML <form>. When the form is sent to the server, it sends the information contained in the fields. The form will trigger a program on the server. This program will extract the information from the fields in the form and process it in some manner.

The server side program may store the information in a database, or search a database to return information.

This process is called the Common Gateway Interface, or CGI.

Information is sent using two methods: 

GET

Sends the information as a "query string." When browsing the Internet, look at the URL in the Address/Location bar. Is there a question mark followed by a lot of information? The part of the URL after the question mark is the query string, and contains a list of name=value pairs. Each pair is separated by an ampersand, and the data is encoded (some characters are converted to hex values). 

A GET limits the amount of information you can pass.

POST

Sends information as a separate file. There is no limit to the amount of information sent.

What is a Servlet?

A Servlet is a direct replacement of the old CGI programs. It is a Java program that is executed on the server when a form is submitted. The servlet will make the decision of what to do next, based on the form that submitted the information.

Creating a Servlet

Important note: Anytime you recompile any java class that is part of your application, you must re-start Tomcat!

The minimum code for creating a servlet is:

import javax.servlet.*;
import javax.servlet.http.*;

public class MinimalServlet extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
      // code to process when form method is GET
   }

   public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
      // code to process when form method is POST
   }

}

Often, the code for a GET and POST is the same. Some programmers will place the code in one method, then call that method from the other. I like to create a "process" method for the code, then have the "doGet" and "doPost" call the "process" method.

The code for my servlet can be viewed here: CIS237Servlet.java.

In my "process" method, I am testing the value of a hidden field in the form. This tells me what process to execute. Then, I have a separate method that is called for each process. Each process method returns a String indication the page the should be re-directed to.

The request Object

This object contains the information stored in the Form or QueryString.

The response Object

This object contains the HTML stream that will be sent back to the browser.

The out object

This object is the actual print stream back to the browser. Recall from the lecture on Sockets that we needed to get the output stream of the socket. This is the same thing.

Forwarding a request/response

The purpose of forwarding is to pass off the next stage of processing to either another Servlet or to a JSP.

This uses the forward() method of the RequestDispatcher class. An instance of a RequestDispatcher can be retrieved from the request object using the getRequestDispatcher() method.

Setting/Getting Attributes

An Attribute is a way of storing variables for a session. In this way, then next stage in a process can retrieve that information.

An Attribute is set by calling the setAttribute() method of the Session object associated with the request object. The setAttribute() method takes two arguments:

  1. A String representing the name of the Atttribute
  2. The Object to be stored.

An Attribute is retrieved using the getAttribute() method of the Session object associated with the request object. The getAttribute() method takes one argument:

  1. A String representing the name of the Attribute

The getAttribute() method returns the Object, which must then be cast to the correct type.

HTML Forms and Calling a Servlet

Calling the Servlet from the Form is easy. Just name the Servlet as the action of the Form:

<form name='myForm' action='myServlet' method='post'>

The Form should have a submit button that sends the data to the server and
triggers the Servlet.

Server-Side Setup

Define the Application for Tomcat:

  1. Open the "server.xml" file in the "Apache Tomcat 4.0\conf" directory with a TEXT editor.
  2. Locate the line that says "<!-- Tomcat Manager Context -->".
  3. Make a copy of that line and the two lines below it. The next two lines start with "<Context" and ends with "/>".
  4. In the new copy, change the word "Manager" to "cis135". NOTE: This is CASE-SENSITIVE.
  5.  Save and close the file.

Create the Folders and Application Files:

  1. Open Windows Explorer and add a directory called "cis135" to the "Apache Tomcat 4.0\webapps" folder. 
  2. Create a new folder inside "cis135" named "WEB-INF". Pay close attention to capitalization. 
  3. Create a new folder inside "WEB-INF" named "classes". Your compiled servlet class must go in this folder.
  4. Download the "web.xml" file and place it in the "WEB-INF" folder.
  5. Open the "web.xml" file in a text editor, and replace "CIS237Servlet" with the actual name of your servlet class.

The purpose of the "web.xml" file is to define the environment of your web application. The <servlet> tag provides a logical to physical mapping. It allows us to provide a name for the servlet that will be typed into the Address/Location bar. That name is mapped to a specific class file.

Page-Flow for the Address Application

The first call to the Servlet passes the "L" command. A Vector containing a list of all items is set as an attribute, then the process is passed from the Servlet to a JSP that will display the list as hyperlinks.

There is a button on the list page for adding a new item. Clicking the button does not pass through the Servlet, it simply loads an HTML form for adding a new item. Clicking the "Add' button on the form passes all fields and the "A" command to the Servlet. Once the add is complete, the process is passed from the Servlet back to the JSP that displays the list as hyperlinks.

When a hyperlinked item is clicked, the item ID and the "R" command is passed to the Servlet.  A JavaBean is populated with the data from the database record, then set as an attribute. The process is passed from the Servlet to a JSP that will display the details.

From the detail view, a "Delete" button may be clicked. This passes the item ID and the "D" command to the Servlet. Once the delete is complete, the process is passed from the Servlet back to the JSP that displays the list as hyperlinks.

From the detail view, an "Edit" button may be clicked. This passes the item ID and the "E" command to the Servlet. The only difference between this and the detail view is that the JSP page contains text fields so that changes can be made.

From the detail edit, an "Update" button may be clicked. This passes all fields and the "U" command to the Servlet. Once the update is complete, the process is passed from the Servlet back to the detail view JSP.