The javax.servlet.http Package |
The javax.servlet.http package provides classes and interfaces that are used to create HTTP protocol-specific servlets. The abstract class HttpServlet is a base class for user-defined HTTP servlets and provides methods to process HTTP DELETE, GET, OPTIONS, POST, PUT, and TRACE requests. The Cookie class allows objects containing state information to be placed on a client machine and accessed by a servlet. The package also enables session tracking through the HttpSession and HttpSessionBindingList interfaces.

HttpServletRequest Interface |
public interface HttpServletRequest extends ServletRequest |

    ServletRequest
          HttpServletRequest

The HttpServletRequest interface extends the ServletRequest interface to provide methods that can be used to obtain information about a request to an HttpServlet.

HttpServletResponse Interface |
public interface HttpServletResponse extends ServletResponse |

    ServletResponse
       HttpServletResponse

The HttpServletResponse interface extends the functionality of the ServletResponse interface by providing methods to access HTTP-specific features such as HTTP headers and cookies.

Example: Using HttpServletResponse

This example uses the HttpServletResponse object that is automatically passed to the doGet() to send a response back to the user. A text field in an HTML page asks for a login name. When the Submit button is pressed, the servlet is invoked. If the login name is determined to be valid (in this case if it is equal to the String "palmer"), the HttpServletResponse object is used to open an output stream back to the client machine. If the login is invalid, the HttpServletResponse object is used to re-direct the client back to the HTML login page.

After loading the HttpServletResponse.html Web page. Type in any random String into the textfield and hit the Submit button. The servlet returns to the HTML login page. Now type in "palmer" and see what happens.

       import javax.servlet.*;
       import javax.servlet.http.*;
       import java.io.*;
       public class HttpResponseServlet extends HttpServlet {
         String login;
         boolean valid = false;
         // The doGet() method is called when the user presses the
         // "Submit" button in the HttpResponseServlet.html Web page.

         // It reads the login name from the query string and sends
         // a response back to the client.
         public void doGet(HttpServletRequest request,
         HttpServletResponse response) throws ServletException,
         IOException {
         // Extract the login name from query string and compare it to
         // a valid entry.
         login = request.getParameter("login");
         if (login.equals("palmer")) {
         valid = true;
         }
         // If the login name is valid (equal to "palmer"), a response is
         // sent back to the client.  If the login is invalid, the
         // HttpSerlvetRequest object re-directs the client back to the
         // login HTML page.
         if (valid) {
         response.setContentType("text/html");
         PrintWriter pw = response.getWriter();
         pw.println("<HTML> <HEAD> <TITLE>HttpRequest Exmaple</TITLE>");

    pw.println("</HEAD><BODY>");
         pw.println("Welcome ");

    pw.println("</BODY></HTML>");
         pw.close();
         } else {
         String str = "/HttpResponseServlet.html";

    response.sendRedirect(response.encodeRedirectURL(str));
         }
         }
       }

The HttpServletResponse.html code is as follows:

       <HTML>
       <HEAD>
       <TITLE> HttpResponse Example </TITLE>
       </HEAD>
       <BODY>
       <FORM METHOD=GET ACTION="http://localhost:8080/servlet/HttpResponseServlet">
       Enter login name
       <INPUT TYPE=TEXT NAME=login ><BR>
       <INPUT TYPE=SUBMIT VALUE=Submit>
       </FORM>
       </BODY>
       </HTML>

HttpSession Interface |
public interface HttpSession |

The HTTP protocol is stateless, meaning that each request is independent and has no knowledge of previous requests. Sometimes, it is desirable to save state information. For instance, the contents of a shopping cart should be known by each request. Http Servlets can maintain this information by way of a session.

The HttpSession interface provides methods that define a session between a client and server. The session lasts for a specified time period and can encompass more than one connection or page request from the user. The methods declared by this interface allow the access of information about the session and enable the binding of objects to sessions. The bound object can contain the state information that is intended to be known by every request.

Example: Using HttpSession

In this example, an HttpSession object is used to monitor the value of a Counter object that is bound to it. The user can increment or re-set the value.

       import javax.servlet.*;
       import javax.servlet.http.*;
       import java.io.*;
       public class SessionServlet extends HttpServlet {
         // The doGet() method is called when the servlet is invoked.
         // It sends a simple form back to the client containing two
         // buttons, one to add to the count and one to clear the count.
         public void doGet(HttpServletRequest request,
         HttpServletResponse response) throws ServletException,
         IOException {

    response.setContentType("text/html");
         PrintWriter pw = response.getWriter();
         pw.println("<HTML> <HEAD> <TITLE> Cookie Example </TITLE>");

    pw.println("</HEAD><BODY>");
         pw.println("<FORM METHOD=POST>");
         pw.println("<INPUT TYPE=SUBMIT NAME=add VALUE=Add><BR>");
         pw.println("<INPUT TYPE=SUBMIT NAME=clear VALUE=Clear><BR>");

    pw.println("</FORM></BODY></HTML>");
         pw.close();
         }
         // The doPost() method is called when either of the two buttons
         // is pressed.
         //
         // This example is set up to run under Java Servlet API 2.1.
         // Under version 2.2, the putValue() method would be replaced
         // by setAttribute() and the getValue() method would be replaced
         // by getAttribute()
         public void doPost(HttpServletRequest request,
         HttpServletResponse response) throws ServletException,
         IOException {
         // A HttpSession object is created if it does not already exist.
         // If the client has not yet accessed the servlet, a Counter object
         // is created and bound to the session.  The Counter object is
         // returned using the getValue() method every time the servlet is
         // accessed.
         HttpSession session = request.getSession(true);
         if (session.isNew()) {
         session.putValue("count", new Counter(0));
         }
         Counter counter = (Counter) session.getValue("count");

         // If the "Add" button was pressed, the count is incremented.
         // If the "Clear" button was pressed, the count is cleared.
         if (request.getParameter("add") != null) {
         counter.addOne();
         } else {
         counter.clear();
         }

    response.setContentType("text/html");
         // Open a character output stream to the client machine and write
         // the current count.  There is also a hyperlink to return to the
         // button page
         char dq = '\"';
         PrintWriter pw = response.getWriter();
         pw.println("<HTML> <HEAD> <TITLE> Session Example </TITLE>");
         pw.println("</HEAD><BODY>");
         pw.println("current amount: " + counter.getCount() + "<BR>");
         pw.print("<A HREF=" + dq);
         pw.print(request.getRequestURI());
         pw.println(dq + ">Return to Buttons</A>");

    pw.println("</BODY></HTML>");
         pw.close();
         }
       }
       // Counter is a simple class that maintains a count.  Methods are
       // provided to increment the count, clear the count, and return
       // the current count value.
       class Counter {
         int count;
         public Counter(int c) {
         count = c;
         }
         public void addOne() {
         ++count;
         }
         public void clear() {
         count = 0;
         }
         public int getCount() {
         return count;
         }
       }

Press the Add button a few times and watch the count increment. The Clear button causes the count to be re-set to zero.

HttpSessionBindingListener Interface |
public interface HttpSessionBindingListener extends EventListener |

    EventListener
      HttpSessionBindingListener

The methods declared in the HttpSessionBindingListener interface are called when an object is bound to or unbound from a registered session.

HttpSessionContext Interface |
public interface HttpSessionContext |
The methods declared in the HttpSessionContext interface (and the interface itself) were deprecated as of Java Servlet API 2.1 for security reasons. This interface will be removed in a future API version and its methods should not be used for new codes.

Cookie Class |
public class Cookie extends Object implements Cloneable |

    Object
        Cookie

Interfaces

Cloneable

A Cookie is an object that resides on a client machine and contains state information. A Cookie has a name, a single value and some other optional information. Cookies can be used to identify a particular user and provide information such as name, address, account number, etc. A cookie is sent by a server to a Web browser, saved on the client machine, and can later be sent back to the server.

The optional information that can be attached to a Cookie includes an expiration date, path and domain qualifiers, a version number, and a comment. The expiration date specifies when the Cookie will be deleted from the client machine. If no date is given, the Cookie is deleted when the session ends.

A servlet sends cookies to a browser using the addCookie() method defined in the HttpServletResponse interface. This method adds fields to the HTTP response header. The browser returns cookies to the servlet by adding fields to the HTTP request header. Cookies can be retrieved from a request by invoking the getCookies() method defined in the HttpServletRequest interface.

Example: Using Cookies

In this example a Cookie is used to store some user data. When the servlet is invoked, the doGet() method returns an HTML file containing textfield and a Submit button to the browser. The method first determines if a Cookie was attached to the request. If it was, the textfield is initialized with the value of the Cookie. If there was no Cookie, the textfield is initially blank.

The user can change the contents of the textfield or leave it the way it is. When the Submit button is pressed, the doPost() method of the servlet is called. This method extracts the contents of the textfield and adds a Cookie containing the textfield contents as its value to the response. The response consists of a confirmation of the textfield contents. The Cookie is set to live on the client machine for five minutes.

       import javax.servlet.*;
       import javax.servlet.http.*;
       import java.io.*;
       public class CookieServlet extends HttpServlet {
         String companyName;
         String value = "";
         // The doGet() method is called when the servlet is invoked.
         // It sends a simple form back to the client.
         public void doGet(HttpServletRequest request,
             HttpServletResponse response) throws ServletException,
         IOException {
         // see if a cookie exists and if it does extract its value.
         Cookie[] cookies = request.getCookies();
         for (int i = 0; i < cookies.length; ++i) {
          String name = cookies[i].getName();
         if (name != null && name.equals("companyName")) {
         value = cookies[i].getValue();
         }
         }
         // Set the response type to html

    response.setContentType("text/html");
         // Open a character output stream to the client machine and write
         // the response.  If a cookie existed, the textfield will be
         // intialized with its value.  Otherwise, the textfield will be blank.
         // Note that the value passed to the textfield is surrounded by
         // double-quotes to allow for multi-word strings.
         char dq = '\"';
         PrintWriter pw = response.getWriter();
         pw.println("<HTML> <HEAD> <TITLE> Cookie Example </TITLE>");

    pw.println("</HEAD><BODY>");
         pw.println("<FORM METHOD=POST>");
         pw.println("Company Name <INPUT TYPE=TEXT NAME=name VALUE=" + dq
         + value + dq + "><BR>");
         pw.println("<INPUT TYPE=SUBMIT VALUE=Submit>");

    pw.println("</FORM></BODY></HTML>");
         pw.close();
         }

         // The doPost() method receives the form from the client and sends
         // back a confirmation.  It also writes a cookie containing the
         // String that was written into the textfield.
         public void doPost(HttpServletRequest request,
         HttpServletResponse response) throws ServletException,
         IOException {
         // Get the contents of the textfield.
         companyName = request.getParameter("name");
         // Create a cookie that contains the contents of the textfield.
         // The cookie is set to live for 5 minutes and is added to the
         // response.
         Cookie nameCookie = new Cookie("companyName", companyName);
         nameCookie.setMaxAge(300);
         response.addCookie(nameCookie);

    response.setContentType("text/html");
         // Open a character output stream to the client machine and write
         // the response
         PrintWriter pw = response.getWriter();
         pw.println("<HTML> <HEAD> <TITLE>" + companyName
         + " information </TITLE>");

    pw.println("</HEAD><BODY>");
         pw.println("Company: " + companyName + "<BR>");

    pw.println("</BODY></HTML>");
         pw.close();
         }
       }

The first time the servlet is invoked, no cookie exists and the textfield is empty. Type something in and press the Submit button. Now, exit the Web browser and shut down the server. Restart the server and reload the servlet into the Web browser. A cookie now exists and the text field will be initialized with whatever was previously typed in to the textfield.

HttpServlet Class |
public abstract class HttpServlet extends GenericServlet implements Serializable |

    Object
       GenericServlet
        HttpServlet

Interfaces

Serializable

The HttpServlet class extends the GenericServlet class to provide functionality tailored to the HTTP protocol. It provides methods for handling HTTP DELETE, GET, OPTIONS, POST, PUT, and TRACE requests. Like the GenericServlet class, the HttpServlet class provides a service() method, but unlike the GenericServlet class the service() method is rarely overridden with HttpServlets. The default implementation of the service() method dispatches the request to the appropriate handler method.

A concrete sub-class of HttpServlet must override at least one of the methods defined in the HttpServlet or GenericServlet classes. The doDelete(), doGet(), doPost(), or doPut() methods are the ones most commonly overridden.

Example: An HttpServlet

This example creates a simple servlet that sends a form back to the client machine. When a login name is submitted from the SampleHttpServlet.html page, the doGet() method of the servlet is called. This method returns a form to the user requesting address information. When the information is entered and the Submit button is pressed, the doPost() method of the servlet is called. This method returns a confirmation of the information that was entered.

       import javax.servlet.*;
       import javax.servlet.http.*;
       import java.io.*;
       public class SampleHttpServlet extends HttpServlet {
         String login, name, address, city, state, zipcode;
         // The doGet() method is called when the user presses the
         // "Submit" button in the SampleHttpServlet.html Web page.
         // It reads the login name from the query string and sends
         // a form back to the client.
         public void doGet(HttpServletRequest request,
         HttpServletResponse response) throws ServletException,
         IOException {
         // Extract the login name from query string
         login = request.getParameter("login");
         // Set the response type to html

    response.setContentType("text/html");
         // Open a character output stream to the client machine and send a
         // form back to the client browser
         PrintWriter pw = response.getWriter();
         pw.println("<HTML> <HEAD> <TITLE>" + name
         + " information </TITLE>");

    pw.println("</HEAD><BODY>");
         pw.println("<FORM METHOD=POST>");
         pw.println("Enter mailing address <BR><BR>");
         pw.println("<TABLE>");
         pw.println("<TR><TD> Name </TD>");
         pw.println("<TD><INPUT TYPE=TEXT NAME=name> </TD></TR>");

         pw.println("<TR><TD> Address </TD>");
         pw.println("<TD><INPUT TYPE=TEXT NAME=address SIZE=20></TD></TR>");
         pw.println("<TR><TD> City </TD>");
         pw.println("<TD> <INPUT TYPE=TEXT NAME=city></TD></TR>");
         pw.println("<TR><TD> <SELECT NAME=state SIZE=1>");
         pw.println("<OPTION VALUE=AZ>AZ</OPTION>");
         pw.println("<OPTION VALUE=CA>CA</OPTION>");
         pw.println("<OPTION VALUE=NY>NY</OPTION>");

    pw.println("</SELECT></TD></TR>");
         pw.println("<TR><TD> Zip Code </TD>");
         pw.println("<TD> <INPUT TYPE=TEXT NAME=zipcode></TD></TR>");
         pw.println("</TABLE>");
         pw.println("<INPUT TYPE=SUBMIT VALUE=Submit>");
         pw.println("</FORM></BODY></HTML>");
         pw.close();
         }
         // The doPost() method is called when the user submits the form.
         // It extracts the address information and returns a confirmation
         // back to the user.
         public void doPost(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException,
         IOException {
         name = request.getParameter("name");
         address = request.getParameter("address");
         city = request.getParameter("city");
         state = request.getParameter("state");
         zipcode = request.getParameter("zipcode");

    response.setContentType("text/html");
         // Open a character output stream to the client machine and write
         // the response
         PrintWriter pw = response.getWriter();
         pw.println("<HTML> <HEAD> <TITLE>" + name
         + " information </TITLE>");

    pw.println("</HEAD><BODY>");
         pw.println("Current mailing address <BR><BR>");
         pw.println(name + "<BR>");
         pw.println(address + "<BR>");
         pw.println(city + ", " + state + "  " + zipcode + "<BR>");

    pw.println("</BODY></HTML>");
         pw.close();
         }
       }

The SampleHttpServlet.html code is the following:

       <HTML>
       <HEAD>
       <TITLE> HttpServlet Example </TITLE>
       </HEAD>
       <BODY>

       <FORM METHOD=GET
         ACTION="http://localhost:8080/servlet/SampleHttpServlet">
       Enter login name
       <INPUT TYPE=TEXT NAME=login ><BR>
       <INPUT TYPE=SUBMIT VALUE=Submit>
       </BODY>
       </HTML>

HttpSessionBindingEvent Class |
public class HttpSessionBindingEvent extends EventObject |

    Object
      EventObject
          HttpSessionBindingEvent

An HttpSessionBindingEvent object is generated whenever an object is bound to or unbound from a session.

HttpUtils Class |
public class HttpUtils extends Object |

    Object
        HttpUtils

The HttpUtils provides three static methods that are useful when developing HTTP servlets.