Module 1 Advanced Java Servlets
Module 1 Advanced Java Servlets
Servlets are small programs that execute on the server side of a web connection. Just as applets
dynamically extend the functionality of a web browser, servlets dynamically extend the
functionality of a web server.
Three methods are central to the life cycle of a servlet. These are init( ), service( ), and destroy( ).
They are implemented by every servlet and are invoked at specific times by the server. Let us
consider a typical user scenario to understand when these methods are called.
First, assume that a user enters a Uniform Resource Locator (URL) to a web browser. The
browser then generates an HTTP request for this URL. This request is then sent to the appropriate
server.
Second, this HTTP request is received by the web server. The server maps this request to a
particular servlet. The servlet is dynamically retrieved and loaded into the address space of the
server.
Third, the server invokes the init( ) method of the servlet. This method is invoked only when the
servlet is first loaded into memory. It is possible to pass initialization parameters to the servlet so
it may configure itself.
Fourth, the server invokes the service( ) method of the servlet. This method is called to process
the HTTP request. You will see that it is possible for the servlet to read data that has been
provided in the HTTP request. It may also formulate an HTTP response for the client. The
service( ) method is called for each HTTP request.
Finally, the server may decide to unload the servlet from its memory
A Simple Servlet
To become familiar with the key servlet concepts, we will begin by building and testing a simple
servlet. The basic steps are the following:
1. Create and compile the servlet source code. Then, copy the servlet’s class file to the proper
directory, and add the servlet’s name and mappings to the proper web.xml file.
2. Start Tomcat.
3. Start a web browser and request the servlet.
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request,ServletResponse response)throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}
First, note that it imports the javax.servlet package.This package contains the classes and
interfaces required to build servlets. Next, the program defines HelloServlet as a subclass of
GenericServlet. The GenericServlet class provides functionality that simplifies the creation of a
servlet.
For example, it provides versions of init( ) and destroy( ), which may be used as is. You
need supply only the service( ) method. Inside HelloServlet, the service( ) method (which is
inherited from GenericServlet) is overridden. This method handles requests from a client. Notice
that the first argument is a ServletRequest object. This enables the servlet to read data that is
provided via the client request. The second argument is a ServletResponse object. This enables the
servlet to formulate a response for the client.
The call to setContentType( ) establishes the MIME type of the HTTP response. In this
program, the MIME type is text/html. This indicates that the browser should interpret the content
as HTML source code.
Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent
to the client as part of the HTTP response. Then println( ) is used to write some simple HTML
source code as the HTTP response.
Compile this source code and place the HelloServlet.class file in the proper Tomcat
directory as described in the previous section. Also, add HelloServlet to the web.xml file, as
described earlier.
The Servlet API
Two packages contain the classes and interfaces that are required to build servlets. These
are javax.servlet and javax.servlet.http. They constitute the Servlet API.
These packages are not part of the Java core packages. Instead, they are standard
extensions provided by Tomcat. Therefore, they are not included with Java SE 6.
The Servlet API has been in a process of ongoing development and enhancement.
The following table summarizes the core classes that are provided in the javax.servlet
package:
The ServletContext interface enables servlets to obtain information about their environment.
Several of its methods are summarized
Object getAttribute(String attr) returns the value of the server attribute named attr.
String getMimeType(String file) returns the MIME type of file.
String getRealPath(String vpath) Returns the real path that corresponds to the virtual path
vpath.
String getServerInfo( ) returns information about the server.
void log(String s) writes s to the servlet log.
void log(String s, Throwable e) writes s and the stack trace for e to the servlet log.
void setAttribute(String attr, Object val) sets the attribute specified by attr to the value
passed in val.
getAttribute(String attr)
getContentType( )
getParameter(String pname)
getParameterNames( )
getParameterValues(String name)
String getServerName( )
void log(String s)
void log(String s, Throwable e)
Here, s is the string to be appended to the log, and e is an exception that occurred.
<html>
<body>
<center>
<form name="Form1"
method="post"
action="PostParametersServlet">
<table>
<tr>
<td><B>Employee</td>
<td><input type=textbox name="e" size="25" value=""></td>
</tr>
<tr>
<td><B>Phone</td>
<td><input type=textbox name="p" size="25" value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</body>
</html>
The HttpServlet class provides specialized methods that handle the various types of
HTTP requests. A servlet developer typically overrides one of these methods. These methods are
doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ). A complete
description of the different types of HTTP requests is beyond the scope of this book. However, the
GET and POST requests are commonly used when handling form input. Therefore, this section
presents examples of these cases.
Here we will develop a servlet that handles an HTTP GET request. The servlet is invoked
when a form on a web page is submitted. The example contains two files. A web page is defined
in ColorGet.htm, and a servlet is defined in ColorGetServlet.java. The HTML source code for
ColorGet.htm is shown in the following listing. It defines a form that contains a select element
and a submit button. Notice that the action parameter of the form tag specifies a URL. The URL
identifies a servlet to process the HTTP GET request.
<html>
<body>
<center>
<form name="Form1" action="ColorGetServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for ColorGetServlet.java is shown in the following listing. The doGet( )
method is overridden to process any HTTP GET requests that are sent to this servlet. It uses the
getParameter( ) method of HttpServletRequest to obtain the selection that was made by the
user. A response is then formulated.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
The HTML source code for ColorPost.htm is shown in the following listing. It is identical to
ColorGet.htm except that the method parameter for the form tag explicitly specifies that the
POST method should be used, and the action parameter for the form tag specifies a different
servlet.
<html>
<body>
<center>
<form name="Form1" method="post" action=" ColorPostServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for ColorPostServlet.java is shown in the following listing. The doPost( )
method is overridden to process any HTTP POST requests that are sent to this servlet. It uses the
getParameter( ) method of HttpServletRequest to obtain the selection that was made by the
user. A response is then formulated.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
Using Cookies
Now, let’s develop a servlet that illustrates how to use cookies. The servlet is invoked when a
form on a web page is submitted. The example contains three files as summarized here:
AddCookie.htm allows a user to specify a value for the cookie named MyCookie.
AddCookieServlet.java processes the submission of AddCookie.htm.
GetCookiesServlet.java displays cookie values.
The HTML source code for AddCookie.htm is shown in the following listing. This page contains
a text field in which a value can be entered. There is also a submit button on the page. When this
button is pressed, the value in the text field is sent to AddCookieServlet via an HTTP POST
request.
<html>
<body>
<center>
<form name="Form1" method="post" action="AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for AddCookieServlet.java is shown in the following listing. It gets the value of
the parameter named “data”. It then creates a Cookie object that has the name “MyCookie” and
contains the value of the “data” parameter. The cookie is then added to the header of the HTTP
response via the addCookie( ) method. A feedback message is then written to the browser.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String data = request.getParameter("data");
Cookie cookie = new Cookie("MyCookie", data);
response.addCookie(cookie);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
}
}
Session Tracking
Several interactions between a browser and a server. Sessions provide such a mechanism.
A session can be created via the getSession( ) method of HttpServletRequest. An HttpSession
object is returned. This object can store a set of bindings that associate names with objects. The
setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of
HttpSession manage these bindings.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
HttpSession hs = request.getSession(true);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
Date date = (Date)hs.getAttribute("date");
if(date != null) {
pw.print("Last access: " + date + "<br>");
}
date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);
}
}