Overview of Servlets and Java Cookies

What are servlets

Recall: Just as applets are small Java programs which run in a web browser on a client machine, servlets are small Java programs that run on a web server. The communication between the browser and the server is as follows: Example: Hello World Example
The HTML source for this page does not indicate that it has been generated by a servlet!

Advantages of server-side request processing:

  1. Servlets can access data on the server without having to transmit the data to the browser.
  2. Servers are fast.
  3. No requirements on the client: it doesn't have to run the latest version of Java or have special plug-ins for the browser.
  4. Servlets can perform a connection to another machine from the server without the client knowing that this connection exists.
  5. More security for the client: Java code is not running on the client machine.
  6. More security of the server's data: it gets accessed only by the server's own code. Only the part that the client needs gets transmitted to the client.

Note that the web server has to be the kind that supports Java Servlet technology. As servlets become more popular, more and more servlet-compatible web servers are produced.

Servlets accomplish tasks which can be done by CGI scripts. The advantage of using servlets over CGIs is that servlets use a standard API, which makes them portable accross platforms. They are easier to write (at least for those familiar with Java) and faster to run. On the downside, servlets need a special kind of servers.

What are servlets used for

Servlets are convenient for:
  1. Server-side request processing, possible with an access to a database or another kind of server-side storage.
  2. Allowing collaboration between people. A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing.
  3. Forwarding requests. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content.

A structure of a Java servlet

A generic servlet in Java implement the interface Servlet. Most servlets, however, extend a class HttPServlet which implements this interface. Your servlets will also extend this class.

To write servlets, you need to import two packages: javax.servlet and javax.servlet.http.

Here is the code for the HelloWorld example (above):


import java.io.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * The simplest possible servlet.
 *
 * @author James Duncan Davidson
 */

public class HelloWorldExample extends HttpServlet {


    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<html>");
        out.println("<head>");

	String title = "Hello World!";

	out.println("<title>" + title + "</title>");
        out.println("</head>");
        out.println("<body bgcolor=\"white\">");
        out.println("<body>");

	out.println("<a href=\"/examples/servlets/helloworld.html\">");
        out.println("<img src=\"/examples/images/code.gif\" height=24 " +
                    "width=24 align=right border=0 alt=\"view code\"></a>");
        out.println("<a href=\"/examples/servlets/index.html\">");
        out.println("<img src=\"/examples/images/return.gif\" height=24 " +
                    "width=24 align=right border=0 alt=\"return\"></a>");
        out.println("<h1>" + title + "</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

When a servlet accepts a call from a client, it receives two objects:

ServletRequest and ServletResponse are interfaces defined by the javax.servlet package. In an HttpServlet the classes HttpServletRequest and HttpServletResponse are used.

In this case, the HTTP request is GET (the default HTTP request), and it is handled in the method doGet(). Other HTTP requests include POST, PUT, and DELETE. They are handled by methods doPost(), doPut(), and doDelete().

The ServletRequest interface allows the servlet access to:

The ServletResponse interface gives the servlet methods for replying to the client. It:

In the example, the response type is set to text/html, and the output is written to the PrintWriter (a kind of a Writer). The method getWriter() of the response was used to get access to the writer. The output is the HTML code for the page generated by the servlet. The two HREF tags are for the two icons which appear in the right upper corner when the applet is executed.

Life cycle of a servlet

Each servlet has the same life cycle:
  1. A server loads and initializes the servlet. When a server loads a servlet, the server runs the servlet's init() method.
  2. The servlet handles zero or more client requests
  3. The server removes the servlet. When a server destroys a servlet, the server runs the servlet's destroy() method (some servers do this step only when they shut down).
Default init() and destroy() methods are used when no such methods are provided in the servlet class.

Getting info from a request

Example: RequestInfoExample servlet Click on the icon at the right upper corner to view the source.

The code that gets request info:


        out.println("Method: " + request.getMethod());
        out.println("Request URI: " + request.getRequestURI());
        out.println("Protocol: " + request.getProtocol());
        out.println("PathInfo: " + request.getPathInfo());
        out.println("Remote Address: " + request.getRemoteAddr());

This is the information associated with a request. You don't need to understand the details of it, just to give you an idea of what it is:

Getting parameters

Example: RequestParamExample servlet

A user can pass a parameter via an HTML form. Note (by looking at the source code of the page) that the form uses the method POST. Therefore the servlet handles it by doPost() method:


    public void doPost(HttpServletRequest request, HttpServletResponse res)
    throws IOException, ServletException
    {
        Enumeration e = request.getParameterNames();
        PrintWriter out = res.getWriter ();
        while (e.hasMoreElements()) {
            String name = (String)e.nextElement();
            String value = request.getParameter(name);
            out.println(name + " = " + value);
        }
    }

The parameters of the request are the data that user enters in the form. Each parameter has a name (defined in the form) and a value (the data that user enters).

The names of the parameters are returned as a Java enumeration type which has methods hasMoreElements() to check if there are more elements and nextElement() to advance to the next element. The name is stored as an object in the enumeration and needs to by typecasted to a String before it can be used as a string.

The values are retrieved by the getParameter() method of the request which takes the name of the parameter as an argument.

In the example, when both the name and the value are retrieved, they are appended to the resulting HTML page via the writer.

Cookies

Example: CookieExample servlet

Session

to be posted
Some material on this page has been adapted from a subset of online sources listed here
This page has been created and is maintained by Elena Machkasova
Comments and suggestions are welcome at emachkas@wellesley.edu

Spring Semester 2002