In this article, we will look provide an overview of the Servlet Technology Model that is the basis for most of the components of the web tier. We will review the HTTP Methods as well as the HttpServletRequest and HttpServletResponse interfaces. This is part of a series of articles to help you prepare for the web component developer exam.

Understanding HTTP Methods and Servlets

The basis for delivering the majority key web technology is HyperText Transport Protocol (HTTP). HTTP is a generic, lightweight, stateless protocol that powers the delivery of content on the World Wide Web. It runs on top of TCP/IP. The TCP part is what ensures that the content which is delivered in pieces arrives as a coherent resource at it’s destination. The IP is the underlying protocol for moving packets of data across the World Wide Web (WWW). As the majority of content consist of the that is used for the delivery of HTML and XML, HTTP is the key protocol for delivering this content.
As HTTP is a stateless protocol it keeps no association between requests. So when a client makes a request to a server, the server will send a response, and the transaction is completed. The next request from the same client is a viewed as a completely separate new transaction wholly unrelated to the first request.

Requests, Responses, and Headers

With HTTP, a client (in most cases a web browser) makes a request to a web server that will process the request and then respond. In the client’s request, the first thing it specifies is an HTTP command or method. This HTTP method tells the server the type of action it wants the server to perform. In addition, the first line of the request also provides the address of a document (a URL) and the version of the HTTP protocol being used. An example of this is shown below:

XML Code: Example of GET Request
GET /home.html HTTP/1.1
In this example, we make a request using the GET method, asking for a document named home.html, using HTTP Version 1.0. After sending the request, the client can also send optional header information providing the server with extra information about the request. This can include the software the client is running as well as the content types it understands. This information although not directly pertinent to the request can be useful in helping the server to generate a response. An examples of a request headers are provided below:

XML Code: Example of Request Header
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows XP) 
Accept: image/gif, image/jpeg, text/*, */*
In this example, we have the User-Agent header that provides information about the client software being used by the client and the Accept header specifying the types of media (MIME) that the client prefers to accept. The client sends a blank line after specifying all the headers they want to send to indicate the end of the header section. Depending on the HTTP method being used, the client has the option of sending additional data to the server. If a request doesn't send any data, it simply ends with an empty line.

Tutorial:Review of Http Methods and Servlet API for Web Component Developer Exam-a13-httprequestresponse.jpg
Figure: Client making HTTP Request and HTTP Response

After the server has processed the client request, it sends back a response. In the first line of the response is the status code specifying the version of the HTTP protocol being used by the server, a status code, and a description of the status code. An example of this is shown below:

XML Code: Response with Status Code and Description
HTTP/1.1 200 OK
In the example shown above, is first the status line indicating a status code of 200. This indicates that the request was successful. In addition a description is provided indicating "OK". This is the most commonly used status code along with status code, 404. It always comes with the description "Not Found" indicating that the requested document could not be found. Below is a table providing a complete list of HTTP status codes.

Tutorial:Review of Http Methods and Servlet API for Web Component Developer Exam-a13-httpstatuscodes.jpg
Table: HTTP Status Codes

After the servers sends the status line, it then sends response headers to provide the client with information about the software running on the server, the content type of the server's response, as well as information about when the content was last updated. An listing for a typical server response is shown below:

XML Code: Typical Server Response
Date: Saturday, 10-Jan-12 09:25:12 GMT 
Server: Tomcat 4.1.37 
MIME-version: 1.1 
Content-type: text/html 
Content-length: 2056
Last-modified: Thursday, 8-Jan-12 11:12:23 GMT
In the listing above, the server header provides information the date, information about the server software, MIME type in the content-type header and the date the content was last modified. Once completed, the server sends a blank line after the headers, to complete the header section. If the request was successful (i.e. status code 200), then the requested data is next sent as part of the response. Otherwise, the response normally will provide human-readable data explaining why the server couldn't fulfill the request.

Http Methods

The process of a client connecting to a server always requires an HTTP request. This common set of requests are known as HTTP methods. There are several different types of requests which a client can make. The client connects to a server and makes an HTTP request. The two most frequently used HTTP methods are GET and POST. The GET method serves to obtain a resource (i.e. a document, a chart, or the results from a database query) and a POST method serves to post data (i.e. registration information, credit card information, chart data, or other information being stored in a database).

Outside of the two most commonly used HTTP methods, the other set of methods for HTTP/1.1 that are available are HEAD, PUT, DELETE, TRACE and OPTION. We will discuss all of these methods below. The HTTP methods don’t all share common properties for the requests that are made. There are some methods which are considered Safe Methods and other methods that can be considered Idempotent Methods. This is determined by the side effects that can possibly crop from using these type of methods.

Safe Methods

Safe methods are those methods in which a user should not expect any side effects from using this particular method. In terms of HTTP methods this corresponds to the GET and HEAD methods. If a user accidentally or purposely makes multiple get requests for the same resource, the system in responding to the HTTP method, should do no other action This behaviour allows for user agents to handle other methods (i.e. POST, PUT and DELETE) in a special way that the user is made aware of the fact that a possibly unsafe action is being requested. You made not be in a position to absolutely ensure that the server does not generate any side-effects as a result of responding to a GET or HEAD request as in certain cases, dynamic resources are a feature of the system. What is important is that from the user perspective, the user can be held responsible for any side-effects of making the request.

Idempotent Methods

When a Http method is considered idempotent, the side-effects of N > 0 of multiple identical requests is handled in the same manner as if for a single request. The methods that are considered idempotent are GET, HEAD, PUT and DELETE as well as OPTIONS and TRACE. The later two should never have any side effects so are considered inherently idempotent. Sometimes it is possible for a sequence of several requests generate side effects even if every Http method executed in the sequence is idempotent. In this way we can speak of a sequence being idempotent or non-idempotent. If the sequence when executed always yields a result and is not altered by re-execution of any part or the whole sequence it is considered idempotent. This also depends on whether there are no concurrent operations are being executed on the same set of resources.

GET Method

A GET method will retrieve any resource that can be identified by a Request-URI. If the Request-URI refers to a data-producing process, then the server process will produce the data and return it as the entity in the response. Note that this is not the source text of the process. The source text of the process will only be output if that is what has been requested by the client. A figure showing the Http GET method is shown below:

Tutorial:Review of Http Methods and Servlet API for Web Component Developer Exam-a13-httpgetmethod.jpg
Figure: HTTP GET Method

You can include search characters in your GET method if required. This will transform the GET method into a "conditional GET" if the request message includes an If-Modified-Since, If-Unmodified-Since, If-Match, If-None-Match, or If-Range header field. What this means that only if the conditions are met that which is described in the header field, should the server send the entity being requested. We use a conditional GET method as a means of reducing unnecessary network traffic by allowing for cached entities to be refreshed without requiring multiple requests or transferring data already held by the client.

You can use a partial GET method with a Range header field if necessary. This will help to reduce network usage by completing partially retrieved entities that a partially held by the client. Finally you can cache the responses to GET requests if it meets the requirements for HTTP caching.

POST Method

The POST method is used to request that the server accept the enclosed information in the request as part of the resource identified by the Request-URI in the Request-Line. The POST request sends all its data, which can be of unlimited length, directly as part of the HTTP request body. The exchange is invisible to the client. This has no impact on the URL. Therefore, you can neither bookmark POST requests nor can you email them. In many cases, you cannot even reload them. This is done purposely to ensure that POST are only sent once to the server. POST is designed to cover the following functions:
  • Providing a block of data in a form that is submitted to a data-handling process;
  • Posting a message to a bulletin board or newsgroup or similar group of articles;
  • Annotating of existing resources;
  • Extending a database through an append operation.

Which function is performed in the POST method is dependent on the server and the Request-URI. The posted data is subordinate to that URI. This is irrespective of the type of data or resource being submitted. Sometimes when data or a resource is submitted by a POST method, it may not create a resource that can be identified by a URI. This depends on whether or not the response includes any resource that can describe the result. The proper response code in these situation is either 200 (OK) or 204 (No Content). In the case where a new resource has been created on the server, the response should be 201 (Created). It should also include information that describes the request status, the resource and provides a location header. In contrast to GET methods, the responses to POST methods cannot be cached unless the proper Cache-Control and Expires header fields are provided. You can use the response status 303 (Other) in order to direct the user agent to retrieve a cacheable resource. Below we have a diagram showing a POST method:

Tutorial:Review of Http Methods and Servlet API for Web Component Developer Exam-a13-httppostmethod.jpg
Figure: Http POST Method

HEAD Method

The HEAD method is similar to the GET method. The key difference between the two is that for a HEAD method, the server should not return a message-body in the response. Otherwise, the information contained in the HTTP headers for the response to a HEAD request or GET request should be identical. We use the HEAD method primarily to obtain meta-information about the resource provided in the request without transferring the resource itself in the body of the response. The most prevalent use for the HEAD method is in testing the validity and accessibility of hypertext links as well as confirming any changes in a resource. It is possible to cache a HEAD request. This is because the response from a HEAD request can be used to update a previous cached resource. Some of the field is may change (as shown in the figure for HTTP POST Method) is Content-Length, Content-MD5, ETag and Last-Modified.

OPTIONS Method

The OPTIONS method is used to request information about the available communication options in the request/response chain identified by the Request-URI. A client can use this to determine the options and/or requirements associated with a resource, or to discover the capabilities of a server without performing any sort of action or retrieval of the resource. The responses to the OPTIONS method are not cacheable.

PUT Method

The PUT method is used to request that a data or a resource be stored at the supplied Request-URI. If there is already an existing resource at the Request-URI the the resource should update the existing resource. For a Request-URI in which there is no existing resource, then the Request-URI should be stored as a new resource by the requesting client. In case a new resource is created, the server should return to the client a response of 201 (Created). If an existing resource is modified, it should return either 200 (OK) or 204 (No Content) response codes to indicate successful completion of the request. If for some reason the resource of the Request-URI could not be created or modified, then an error response providing information on the nature of the problem should be presented. Whatever you do, don’t allow the client to ignore any Content-* (e.g. Content-Range) headers that it does not understand. Instead return a 501 (Not Implemented) response in such cases. PUT method responses are not cacheable and any resources identified with this Request-URI should be treated as state.

DELETE Method

The DELETE method is used to request that the server delete the resource identified in the Request-URI. You can override this method on the server when required. It is not possible for the client to guarantee this operation has been carried out irrespective of the status code returned by the server. The server will indicate success unless the resource is not accessible or the server is already in the process of deleting the resource. The status response for the deleting the resource successfully is 200 (OK) including the information describing the status. If you are just acknowledging the reception of the DELETE request, you use 202 (Accepted). If the action has been completed but there is no information in the response, you use 204 (No Content). DELETE Method responses are not cacheable and any resources identified with this Request-URI should be treated as state.

TRACE Method

The TRACE method is probably the least used method of all Http methods. It is used to invoke a remote, application-layer loopback of the request message. Another way of putting it is that it returns to the requesting client the exact contents of its request. This means that the TRACE method allows the client to see what is being received at the other end of the request chain and use that data for testing or diagnostic information. The final recipient of the TRACE request should always reflect back the message received to the client as the resource-body of a 200 (OK) response. The final recipient is either the
server or the proxy or gateway to receive a Max-Forwards value of zero (0) in the request . You must never include a resource in a TRACE request. The response to a TRACE method request should have the entire request message as part of the response body, using Content-Type “message/http”, as long as the original request is valid. TRACE method responses must never be cached.

CONNECT Method

The CONNECT method is a specially reserved name to be used with a proxy that can dynamically switch to being a tunnel. This is very important for SSL tunneling.

What are Servlets

In order to provide extensible server side function, the development team for Java introduced servlets as a key component of server-side Java development. Servlet are small, pluggable extensions to a server that provides numerous enhancements to the server's functionality. With servlets you can easily extend and customize any Java- enabled server. It is a java class that is loaded dynamically into a server to provide additional function. It runs in a Java Virtual Machine (JVM) on the server so is protected from possible security attacks while also prevented from attacking other systems. They can only operate within the JVM on the server. The figure below demonstrates the server architecture.

Tutorial:Review of Http Methods and Servlet API for Web Component Developer Exam-a13-servletarchitecture.jpg
Figure: Servlet Architecture

The Servlet API

Building upon our understanding of HTTP, we will now discuss the Servlet API. The Servlet API is used to create HTTP servlets, or if so desired other types of servlets as well. The packages that hold all of the classes and interfaces used for Servlets is the javax.servlet and javax.servlet.http packages. The javax.servlet package contains classes used to support the creation of generic, protocol-independent servlets. The package javax.servlet.http package holds classes and interfaces which extend the generic protocol independent classes and interfaces specifically for HTTP-specific functionality.

There are two servlets that are used as the base for all servlets that are created. They are javax.servlet.GenericServlet and javax.servlet.http.HttpServlet. Both of these servlets implement the javax.servlet.Servlet interface. If you are looking to create a protocol-independent servlet the you should subclass GenericServlet, while to create a HTTP servlet subclass HttpServlet. Note that the HttpServlet is a subclass of GenericServlet with the addition of HTTP functionality added. The servlet provides certain methods which are automatically invoked by the server process to handle requests. When a server receives a request, it turns around and dispatches it to a servlet and invokes the servlet’s service() method. If you are using a GenericServlet as a base class you will need to override the service() method in order to properly process the requests sent to your servlet. The service() method has two parameters: a request object and a response object. The request object has the relevant information about the request including any data that has been submitted with the request. The response object is used to provide a response to the client that has made the request. The figure below provides an example of this process:

Tutorial:Review of Http Methods and Servlet API for Web Component Developer Exam-a13-genericservlet.jpg
Figure: GenericServlet

An HTTP servlet generally does need to override the service() method. Instead the service() method is mapped to the corresponding HttpServlet method that matches the Http Method of the Http request. If the Http method is a GET request, the server will dispatch it to the doGet() method. If the Http method is a POST request, the server will dispatch it to the doPost method. As with the service() method for a GenericServlet, the developer must override the relevant doXXX() method in order to properly process the HTTP request. You only need override the methods that your HTTP servlet will be required to handle. You can use the default implementations for any methods that you are not expecting your servlet to handle. can override either or both of these methods, depending on the type of requests it needs to handle. The service() method of HttpServlet will handle the setup and dispatching to all the doXXX() methods. I should say that the only other methods that you may want to override are the doPut() and doDelete() methods. In general it is not recommended to override the default implementations of doHead(), doTrace() or doOptions(). In 99% of the cases, the default implementation will suffice for your needs. The figure below shows a HttpServlet.

Tutorial:Review of Http Methods and Servlet API for Web Component Developer Exam-a13-httpservletallmethods.jpg
Figure: HttpServlet Handling all Http Methods

Outside of the GenericServlet and HttpServlet classes in the javax.servlet and javax.servlet.http packages, there are a number of largely support classes that are available for your use. There are classes for ServletRequest and ServletResponse as well as classes for HttpServletRequest and HttpServletResponse so that you have all the functionality available to your for handling either generic or Http requests and responses. As well you have in the javax.servlet.http package an HttpSession class for managing and tracking a session and a Cookie class so that you can easily set up and manage HTTP cookies.

Generating a Page Using HttpServlet

The most simple thing for which we use a HttpServlet is to generate a HTML page. A servlet can be used for a variety of tasks such as generating a HTML page, processing a HTML form, generating a report from a database, checking identities, etc. To start out we will demonstrate the basics of using a HttpServlet in order to create a HTML page in the next section.

Creating a Hello Acme Page

We will use a HttpServlet to generate a complete HTML page. It will not have much functionality except generating “Hello Acme” `HTML page when we access the servlet via a web browser. The servlet, called AcmeServlet extends the HttpServlet class as was described in the previous section and we will override the doGet() method in order to process the request. So now every time the web server receives a GET request for this servlet, the server invokes this doGet() method, passing it an HttpServletRequest object and an HttpServletResponse object. The client’s Http request is encapsulated in the HttpServletRequest object. It holds all the information about the client’s request including the HTTP headers, any parameters, session, etc. Below is the listing for the HelloAcme servlet:

Java Code: Code for HelloAcme Servlet
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloAcme
 */
@WebServlet(description = "Hello Acme Servlet", urlPatterns = { "/HelloAcme" })
public class HelloAcme extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloAcme() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<HTML>"); 
		out.println("<HEAD><TITLE>Hello Acme</TITLE></HEAD>"); 
		out.println("<BODY>"); 
		out.println("<BIG>Hello Acme</BIG>"); 
		out.println("</BODY></HTML>");
	}

}
Running Hello Acme

Now we will run the servlet. I’m running the servlet in Eclipse with the Eclipse Java EE IDE for Web Developers. I have also installed JBoss 6.1 Application Server. For the sake of brevity I will not go into the details of the setup and configuration. Basically you will need to have the latest version of the Java Servlet Development Kit (JSDK) and the corresponding Java Development Kit in order to run the servlet. Finally you will need a browser but I don’t think that this is a problem if you’re reading this. Below is the screen when the servlet is run.

Tutorial:Review of Http Methods and Servlet API for Web Component Developer Exam-a13-helloacmebrowser.jpg
Figure: Web Browser Showing Output from HelloAcme Servlet

In Eclipse, many of the details of deploying a servlet are automated. In the figure above, you can see that the URL that you need to use is: http://localhost:8080/HelloAcme/HelloAcme. You need to check with the documentation for your application server provider in order o determine what is the name of your server or if it is localhost because you are running your server on a local machine.

If you look at the code, you will see an annotation before the class declaration for the servlet. The @WebServlet annotation allows you to declare your web servlet as well as provide a description and an alias. This is an alternate way to refer to a servlet than by its registered name. Before you were required to do all of this in the web.xml document, but now similarly to the functionality available for using annotations in EJBs, you have similar functionality available for your dynamic web applications.

How to Handle Form Data with a GET Request

Now we are going to look at some of the power of servlets. Rather than just print out a “Hello Acme” page from a servlet, we are going to retrieve form parameters from a page, process them and then return a response related to the form. In order to do this we need to create a HTML form. In this form, we will ask the user what is their favorite football team and retrieve it in a servlet. The listing for the page is shown below:

XML Code: FootForm HTML with GET Action
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Foot Form</title>
</head>
<body>
<form method="get" action="ServletEx/Football">Can you tell me the name 
of your favorite football team?<input type=text name="name"><p>
<input type=submit></form>
</body>
</html>
Figure below shows how the page appears in a web browser.

Tutorial:Review of Http Methods and Servlet API for Web Component Developer Exam-a13-footformbrowser.jpg
Figure: HTML FootForm Page

The user enters the name of their favorite football team and then submits the form. The name is sent to the Football servlet. You can see this in the code by looking at the because we've set the get attribute to point to the servlet. As the form uses the GET method, there will be a query string that is appended to the request URL. In our case, if the user entered, Tottenham Hotspurs, the the full URL would be http://server:8080/servletEx/Footbal...enham+Hotspurs. Note that the space between the two parts of the name of the football is specially encoded as a plus sign by the browser since URLs are not allowed to contain spaces.

How to Handle Form Data using a POST Request

Next is the servlet for handling the HTTP request that is returned from the user clicking on submit. The servlet’s HttpServletRequest object will contain the form data in its query string. In our example the servlet must be able to access and read the “name” parameter from the FootForm. This is shown in the code for the servlet below:

Java Code: Code for Football Servlet
/**
 * Servlet implementation class Football
 */
@WebServlet(description = "Find a person's favorite football team", urlPatterns = { "/Football" })
public class Football extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
@see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html"); 
		PrintWriter out = response.getWriter();
		String name = request.getParameter("name"); 
		out.println("<HTML>"); 
		out.println("<HEAD><TITLE>Damn good team, “ + name + “</TITLE></HEAD>"); 
		out.println("<BODY>");
		out.println("Go, " + name + “!”); 
		out.println("</BODY></HTML>");
	}

	@Override
	public String getServletInfo() {
	   return "Servlet that knows the name of a person's favorite football team";	
	}

}

The key thing to note in this servlet is the call to request.getParameter(“name”) in order to access the parameter for the name of the football team. We then use this in printing out the message of support for the team (i.e. “Go Tottenham Hotspurs!”). In general we use the getParameter() method in order to provide the servlet access to the parameters in its query string. Either the method will return null if there is no parameter query string being specified or it will return the parameter's value for the query string. In the case that no value was specified for the parameter, like if the form has not been filled in, then the getParameter() will return an empty string.

The getServletInfo() method is one of the support methods that we spoke about earlier that is available to a developer. You can override this method in order to return descriptive information about the servlet including its purpose, version, copyright as well as the name of the author. The output of entering “Tottenham Hotspurs” into the form and clicking submit is shown below:

Tutorial:Review of Http Methods and Servlet API for Web Component Developer Exam-a13-footformresponse.jpg
Figure: Football Servlet with Form Data

If you wanted to use an HTTP Post method as well as HTTP GET method, we can change the Football servlet to handle POST without requiring a radical refactoring of the servlet. All that is required is to dispatch all POST request to the doGet method. The code below shows how this is accomplished:

Java Code: doPost dispatching to doGet Method
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	doGet(request, response);
}
So if you now wanted to use a POST method to handle form submissions to the Football servlet, you could do the following:

XML Code: Form Method with Post Action
<form method=post action="/ServletEx/Football">
Whether you decide to use a GET method or POST method is more depending on what you are looking to achieve. From a semantic perspective, your operations should be consistent with the verbs being used. If you are doing a GET request, you should be accessing a resource. If you are doing a POST request, you should be updating or creating a new resource. In terms of the servlet, since the last change to HTTP, there is little difference in the ability of each HTTP method to accept large amounts of input. What matters is that in relation to GET, it should be used to facilitate access to a resource whereas for a POST, it should be related to accessing as well as updating a resource.

How to Handle a HEAD Request

It is very easy to handle HEAD requests using Servlets. This is because rather than a developer be forced to handle a doHead method(), instead the HttpServlet automatically supports HEAD requests via the doGet method. This is because the service() method of the HttpServlet identifies HEAD requests, constructs a modified HttpServletResponse object with all the header information and then passes it along with the unchanged request, to the doGet() method. After the doGet() method is invoked and any processing is done, it is only the headers that it has set that are returned to the client. The modified HttpServletResponse object effectively suppresses all body output.∗ Figure 2-6 shows how an HTTP servlet handles HEAD requests.

Tutorial:Review of Http Methods and Servlet API for Web Component Developer Exam-a13-headrequesttoservlet.jpg
Figure: Head Request to a Servlet

If you want to further improve performance on this strategy, you can detect the HEAD requests in the doGet() method, and short circuit writing output that will never be seen by returning the header earlier. An example of how to do using the getMethod() method is shown for the Football servlet.

Java Code: doGet() Method for handling HEAD Request
/**
 * Servlet implementation class Football
 */
@WebServlet(description = "Find a person's favorite football team", urlPatterns = { "/Football" })
public class Football extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
@see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html"); 
		if(request.getMethod().equals(“HEAD”))
			return;

		// Otherwise proceed as for a GET Method
		PrintWriter out = response.getWriter();
		String name = request.getParameter("name"); 
		out.println("<HTML>"); 
		out.println("<HEAD><TITLE>Damn good team, “ + name + “</TITLE></HEAD>"); 
		out.println("<BODY>");
		out.println("Go, " + name + “!”); 
		out.println("</BODY></HTML>");
	}

	@Override
	public String getServletInfo() {
	   return "Servlet that knows the name of a person's favorite football team";	
	}

}
Note that we set the Content-Type header irrespective of whether it is a GET or HEAD request. There are other header values that may not be available until a response is actually calculated. For example, the would be no way of knowing the Content-Length, but there is no problem with the Content-Type. Depending on what information you are looking to obtain, this may be a useful algorithm for your development. Finally if the conditional statement for the getMethod returns information that it is a HEAD request, we use the return statement to exit the doGet() method.

A Look at Servlet Containers

All servlets are controlled by the web container. Similar to an EJB container, the web container provides a number of services that it uses to manage and run the servlets within it. These services are:
  • Lifecycle Management - The container controls the lifecycle of the servlet. It loads the classes, instantiates and initializes the servlets, invokes the servlets methods and makes it available for garbage collection at the end of it’s active life.
  • Communications Support - The container facilitates communication between the web server and the servlets. This helps the developer to avoid the need to deal with low level socket communications. Instead the container knows the protocol between the server and itself, thus freeing the developer to focus on business logic and not the API of the web server that they are using.
  • Multithreading Support - The container creates automatically new threads in Java to handle each servlet request it receives. When the servlet has completed it work, by returning from the service() method invocation, the thread completes.
  • Declarative Security - The container provides security that is easy to configure via an XML deployment descriptor. This allows you to avoid the need to hard code this information into your servlet or other application classes.
  • JSP Support - The container provides support for JavaServerPages by transforming the JSPs into Java code that it then compiled.


The LifeCycle of Servlets

The servlet lifecycles has it’s parallel in the world of Enterprise Java Beans (EJBs). It is a highly flexible means of allowing servlet engines to manage performance, security and resource problems within the servlet environment. All servlets will execute within the same Java Virtual machine which allows them to share data with each while through Java classes shielding private data from one another. At the same time, servlets can continue in an initialized state between requests since this doesn’t take up a great deal of memory. There are only two states for a servlet; Does not exist or initialized. In the initialized state, the servlet is ready to receive requests from the server by the container invoking the service() method. A figure representing the servlet lifecycle is shown below:

Tutorial:Review of Http Methods and Servlet API for Web Component Developer Exam-a13-servletlifecycle.jpg
Figure: The Servlet Lifecycle

The steps that are performed by the container for the servlet is shown below:
  1. Create and initialize the servlet.
  2. The servlet handles zero or more service calls from clients.
  3. When a service method call is terminated, the container can allow the servlet to remain in instantiated state or it can destroy the servlet and set it to garbage collected.


Note that a servlet can be loaded, created and instantiated and then be destroyed and garbage collected without ever handling any client request. Most vendors have algorithms for servlet lifecycle to ensure that servlets are only initialized when it is necessary to handle service requests.

Using the HttpServletRequest Object

The process of using a Http Servlet involves a client sending a Http message to the server. The basic role of a servlet is to take a clients request, do some processing and then return a response to the client. It does this once it’s service() method has been invoked by the container, by calling the relevant doXXX() method. A HttpServletRequest is created in order to provide the developer with all of the relevant information need to access and use this data effectively.

Tutorial:Review of Http Methods and Servlet API for Web Component Developer Exam-a13-getrequesttext.jpg
Figure: A GET Request

If you look at the figure above, you’ll see that the first part of the HTTP GET request is known as the request header. Here we have all the information needed to complete a request. The request header is composed of four parts;
  • Request Method (in this case a GET method)
  • URI - the part of URL for the resource being retrieved (tudo/getTodo.jsp)
  • Query String - this is specific to a GET method where additional information can be provided.
  • Version of the protocol that should be used (in this case HTTP 1.1)

This is the only part of the request header required to create a make request. You can retrieve this information by using the numerous functions available in the HttpServlet API. See the diagram below for some of the more commonly used functions for access all the information provided in a request including cookie and session information for Http Requests.

Tutorial:Review of Http Methods and Servlet API for Web Component Developer Exam-a13-servletrequestclass.jpg
Figure: Hierarchy of ServletRequest and HttpServletRequest

Below this is provided additional information about the client, the type of browser and language preferences. This permits the server to handle the request in the best way to satisfy the client. The last section can include parameter information that may be specific to the request. This is only done in POST Request. A POST request is conventionally used to process an HTML form since in general this is for updating or creating a new resource. The example of a POST is shown below:

Tutorial:Review of Http Methods and Servlet API for Web Component Developer Exam-a13-postmethodtext.jpg
Figure: A POST Request

In general the rule is that for reading data into the browser use GET. For every page requested by a browser that does not specify a request method, it will default to the GET method. The GET request method was intended for reading data only. But often with database applications even to read data it is necessary to provide parameter data by appending information to the URL (i.e., -/getTodo.jsp?todoId=23459). The GET will forward data in a form that is visible to the user and that can be caced as well as bookmarked. Previously there was a maximum length for a URL to limit the amount of parameter data. But with the inception of REST based services and the update to HTTP, this limit has been eliminated.

If you are looking to send data to a resource, you should use a POST method. In this case, the POST method will append name-value pairs in the HTTP request. As can be seen in the figure above, the POST data is within the request, but it is not viewable by the user. Therefore it is not possible to neither cache nor bookmark it. Even before the changes to HTTP, you were allowed to have unlimited parameter data in a POST request. For JSPs, parameter data is accessed in exactly the same manner irrespective of whether GET or POST is used. It is left to the JSP developer to best determine what request method meets their requirements.

The HTTP Response

The purpose of the HttpServletResponse object is to handle what and how the server responds to a request. The data is sent back in a standard “response” format. The response consist of the following information:
  • Status line - Containing protocol, status integer and optionally a description
  • Response headers - Values such as cache-control, pragma, connection, retry-after, expires, location, www-authenticate and content-encoding.
  • Body - the actual data of the response


In general, You call setContentType to set the MIME type of the response, then you call getWriter to obtain an output stream and then you do some Input/Output in order to write in some language (i.e. HTML, MP3, etc) to the stream content back to the client. The three most commonly used methods for the response object are:
  • setContentType() - sets the content type of the response to be the specified type. For a HTTP servlet, it will set the Content-Type HTTP header
  • getOutputStream() - returns a ServletOutputStream for writing binary response data.
  • getWriter() - returns a PrintWriter for writing character-based response data. The writer encodes the characters a(the default is ISO-8859-1 or Latin-1) according to whatever charset is given in the content type.

The figure below shows the classes with most commonly used methods:

Tutorial:Review of Http Methods and Servlet API for Web Component Developer Exam-a13-servletresponseclass.jpg
Figure: Hierarchy of ServletResponse and HttpServletResponse

The status line will indicate the success or failure of the results. After the status line are the name/value pairs representing the response headers. They are used to describe the server, send additional information, or ask the client to take specific actions. The last part is the streaming of the requested document as part of the response body. Note that you could have a text stream or a binary stream dependent on your needs. Review Java documentation for more information about streaming using your HttpServletResponse. In most cases, this will be a single HTML document or several multipart MIME sections. A typical HTTP response is shown below:

XML Code: Typical HTTP Response
HTTP/1.1 200 OK Date: Sun, 08 Dec 1999 18:16:31 GMT Server: Apache/1.3.9 (Unix) ApacheJServ/1.0 
Last-Modified: Tue, 22 Jun 1999 05:12:38 GMT ETag: "d828b-371-376f1b46" 
Accept-Ranges: bytes Connection: close Content-Type: text/html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Final//EN"> 
<HTML> 
<HEAD>
 <TITLE>Football Preference </TITLE>
 </HEAD> 
<BODY COLOR="#ffffff"> My Favorite Team is Liverpool, Go Reds!
</BODY>
</HTML>
Conclusion

In closing, we covered a great deal of ground about the servlet technology model going from the HTTP Methods that are available through the servlet lifecycle and ending with the HttpServletRequest and HttpServletResponse objects. In the next article we will cover the structure and deployment of web applications including advances that have been made in order to simplify the deployment process.