0% found this document useful (0 votes)
34 views

Slide 9 Servlet API

The document discusses the core packages and classes that make up the Servlet API - javax.servlet and javax.servlet.http. It provides tables summarizing key interfaces like Servlet, ServletRequest, ServletResponse, and classes like GenericServlet. All servlets must implement the Servlet interface. The ServletRequest and ServletResponse interfaces enable servlets to obtain information about requests and formulate responses.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Slide 9 Servlet API

The document discusses the core packages and classes that make up the Servlet API - javax.servlet and javax.servlet.http. It provides tables summarizing key interfaces like Servlet, ServletRequest, ServletResponse, and classes like GenericServlet. All servlets must implement the Servlet interface. The ServletRequest and ServletResponse interfaces enable servlets to obtain information about requests and formulate responses.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

The Servlet API

Two packages contain the classes and interfaces that are required to build the
servlets. These are
• javax.servlet
• javax.servlet.http.

They constitute the core of the Servlet API. Keep in mind that these packages are
not part of the Java core packages. Therefore, they are not included with Java SE.
Instead, they are provided by Tomcat. They are also provided by Java EE.
The Servlet API has been in a process of ongoing development and enhancement.
The current servlet specification is version 3.1. However, because changes
happen fast in the world of Java, you will want to check for any additions or
alterations. This chapter discusses the core of the Servlet API, which will be
available to most readers and works with all modern versions of the servlet
specification.

The javax.servlet Package


The javax.servlet package contains a number of interfaces and classes that
establish the framework in which servlets operate. The following table
summarizes several key interfaces that are provided in this package. The most
significant of these is Servlet. All servlets must implement this interface or
extend a class that implements the interface.
The ServletRequest and ServletResponse interfaces are also very important.
The following table summarizes the core classes that are provided in
the javax.servlet package:

Let us examine these interfaces and classes in more detail.

The Servlet Interface


All servlets must implement the Servlet interface. It declares the init( ), service(
), and destroy( ) methods that are called by the server during the life cycle of a
servlet. A method is also provided that allows a servlet to obtain any initialization
parameters. The methods defined by Servlet are shown in Table 38-1.
The init( ), service( ), and destroy( ) methods are the life cycle methods of the
servlet. These are invoked by the server. The getServletConfig( ) method is
called by the servlet to obtain initialization parameters. A servlet developer
overrides the getServletInfo() method to provide a string with useful information
(for example, the version number). This method is also invoked by the server.
The ServletConfig Interface
The ServletConfig interface allows a servlet to obtain configuration data when it
is loaded. The methods declared by this interface are summarized here:

The ServletContext Interface


The ServletContext interface enables servlets to obtain information about their
environment. Several of its methods are summarized in Table 38-2.

The ServletRequest Interface


The ServletRequest interface enables a servlet to obtain information about a
client request. Several of its methods are summarized in Table 38-3.

The ServletResponse Interface


The ServletResponse interface enables a servlet to formulate a response for a
client. Several of its methods are summarized in Table 38-4.

Method : Description
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 (i.e., absolute) path that corresponds to the
relative 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.
The GenericServlet Class
The GenericServlet class provides implementations of the basic life cycle
methods for a servlet. GenericServlet implements
the Servlet and ServletConfig interfaces. In addition, a method to append string
to the server log file is available. The signatures of this method are shown here:
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.

The ServletInputStream Class


The ServletInputStream class extends InputStream. It is implemented by the
servlet container and provides an input stream that a servlet developer can use to
read the data from a client request. In addition to the input methods inherited
from InputStream, a method is provided to read bytes from the stream. It is
shown here:
int readLine(byte[ ] buffer, int offset, int size) throws IOException
Here, buffer is the array into which size bytes are placed starting at offset. The
method returns the actual number of bytes read or –1 if an end-of-stream
condition is encountered.

The ServletOutputStream Class


The ServletOutputStream class extends OutputStream. It is implemented by
the servlet container and provides an output stream that a servlet developer can
use to write data to a client response. In addition to the output methods provided
by OutputStream, it also defines the print( ) and println( ) methods, which
output data to the stream.

The Servlet Exception Classes


javax.servlet defines two exceptions. The first is ServletException, which
indicates that a servlet problem has occurred. The second
is UnavailableException, which extends ServletException. It indicates that a
servlet is unavailable.

Reading Servlet Parameters


The ServletRequest interface includes methods that allow you to read the names
and values of parameters that are included in a client request. We will develop a
servlet that illustrates their use. The example contains two files. A web page is
defined in PostParameters.html, and a servlet is defined
in PostParametersServlet.java.
The HTML source code for PostParameters.html is shown in the following
listing. It defines a table that contains two labels and two text fields. One of the
labels is Employee and the other is Phone. There is also a submit button. Notice
that the action parameter of the form tag specifies a URL. The URL identifies the
servlet to process the HTTP POST request.
<html>
<body>
<center>
<form name="Form1" method="post"
action="http://localhost:8080/examples/servlets/
servlet/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 source code for PostParametersServlet.java is shown in the following
listing. The service( ) method is overridden to process client requests.
The getParameterNames( ) method returns an enumeration of the parameter
names. These are processed in a loop. You can see that the parameter name and
value are output to the client. The parameter value is obtained via
the getParameter( ) method.

import java.io.*; import java.util.*; import javax.servlet.*;


public class PostParametersServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response)throws
ServletException, IOException {
// Get print writer.
PrintWriter pw = response.getWriter();
Get enumeration of parameter names. Enumeration e = request.getParameterNames();

Display parameter names and values. while(e.hasMoreElements()) {

String pname = (String)e.nextElement(); pw.print(pname + " = ");


String pvalue = request.getParameter(pname); pw.println(pvalue);
}
pw.close();
}
Compile the servlet. Next, copy it to the appropriate directory, and update
the web.xml file, as previously described. Then, perform these steps to test this
example:
Start Tomcat (if it is not already running).
Display the web page in a browser.
Enter an employee name and phone number in the text fields.
Submit the web page.

After following these steps, the browser will display a response that is
dynamically generated by the servlet.

The javax.servlet.http Package


The preceding examples have used the classes and interfaces defined
in javax.servlet, such as ServletRequest, ServletResponse,
and GenericServlet, to illustrate the basic functionality of servlets. However,
when working with HTTP, you will normally use the interfaces and classes
in javax.servlet.http. As you will see, its functionality makes it easy to build
servlets that work with HTTP requests and responses.

The following table summarizes the interfaces used in this chapter:


Interface : Description
HttpServletRequest : Enables servlets to read data from an HTTP request.
HttpServletResponse : Enables servlets to write data to an HTTP response.
HttpSession : Allows session data to be read and written.
The following table summarizes the classes used in this chapter. The most
important of these is HttpServlet. Servlet developers typically extend this class
in order to process HTTP requests.

Class : Description
Cookie : Allows state information to be stored on a client machine.
HttpServlet : Provides methods to handle HTTP requests and responses.

The HttpServletRequest Interface


The HttpServletRequest interface enables a servlet to obtain information about
a client request. Several of its methods are shown in Table 38-5.

The HttpServletResponse Interface


The HttpServletResponse interface enables a servlet to formulate an HTTP
response to a client. Several constants are defined. These correspond to the
different status codes that can be assigned to an HTTP response. For
example, SC_OK indicates that the HTTP
request succeeded, and SC_NOT_FOUND indicates that the requested resource
is not available. Several methods of this interface are summarized in Table 38-6.

The HttpSession Interface


The HttpSession interface enables a servlet to read and write the state
information that is associated with an HTTP session. Several of its methods are
summarized in Table 38-7. All of these methods throw
an IllegalStateException if the session has already been invalidated.
The Cookie Class
The Cookie class encapsulates a cookie. A cookie is stored on a client and
contains state information. Cookies are valuable for tracking user activities. For
example, assume that a user visits an online store. A cookie can save the user’s
name, address, and other information. The user does not need to enter this data
each time he or she visits the store.
A servlet can write a cookie to a user’s machine via the addCookie( ) method of
the HttpServletResponse interface. The data for that cookie is then included in
the header of the HTTP response that is sent to the browser.

The names and values of cookies are stored on the user’s machine. Some of the
information that can be saved for each cookie includes the following:
The name of the cookie
The value of the cookie
The expiration date of the cookie
The domain and path of the cookie

The expiration date determines when this cookie is deleted from the user’s
machine. If an expiration date is not explicitly assigned to a cookie, it is deleted
when the current browser session ends.
The domain and path of the cookie determine when it is included in the header of
an HTTP request. If the user enters a URL whose domain and path match these
values, the cookie is then supplied to the web server. Otherwise, it is not.

There is one constructor for Cookie. It has the signature shown here:
Cookie(String name, String value)
Here, the name and value of the cookie are supplied as arguments to the
constructor. The methods of the Cookie class are summarized in Table 38-8.
The HttpServlet Class
The HttpServlet class extends GenericServlet. It is commonly used when
developing servlets that receive and process HTTP requests. The methods defined
by the HttpServlet class are summarized in Table 38-9.

Method : Description

Object clone( ) : Returns a copy of this object.

String getComment( ) : Returns the comment.

String getDomain( ) : Returns the domain.

int getMaxAge( ) : Returns the maximum age (in seconds).

String getName( ) : Returns the name.

String getPath( ) : Returns the path.

boolean getSecure( ) : Returns true if the cookie is secure. Otherwise, returns false.

String getValue( ) : Returns the value.

int getVersion( ) : Returns the version.

boolean isHttpOnly(?) : Returns true if the cookie has the HttpOnly attribute.

void setComment(String c) : Sets the comment to c.

void setDomain(String d) : Sets the domain to d.

void setHttpOnly(boolean httpOnly) : If httpOnly is true, then the HttpOnly attribute is added
to the cookie. If httpOnly is false, the HttpOnly attribute is removed.
void setMaxAge(int secs) : Sets the maximum age of the cookie to secs. This is the number of
seconds after which the cookie is deleted.

void setPath(String p) : Sets the path to p.

void setSecure(boolean secure) : Sets the security flag to secure.

void setValue(String v) : Sets the value to v.

void setVersion(int v) : Sets the version to v.

Table 38-8 The Methods Defined by Cookie


Handling HTTP Requests and Responses
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.
Handling HTTP GET Requests
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.html, and a servlet is defined
in ColorGetServlet.java. The HTML source code for ColorGet.html 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="http://localhost:8080/examples/servlets/servlet/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();
}

Compile the servlet. Next, copy it to the appropriate directory, and update
the web.xml file, as previously described. Then, perform these steps to test this
example:
Start Tomcat, if it is not already running.
Display the web page in a browser.
Select a color.
Submit the web page.

After completing these steps, the browser will display the response that is
dynamically generated by the servlet.
One other point: Parameters for an HTTP GET request are included as part of the
URL that is sent to the web server. Assume that the user selects the red option
and submits the form. The URL sent from the browser to the server is
http://localhost:8080/examples/servlets/servlet/ColorGetServlet?color=Red
The characters to the right of the question mark are known as the query string.

Handling HTTP POST Requests


Here we will develop a servlet that handles an HTTP POST 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 ColorPost.html, and a servlet is defined
in ColorPostServlet.java.
The HTML source code for ColorPost.html is shown in the following listing. It
is identical to ColorGet.html 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="http://localhost:8080/examples/servlets/servlet/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();
}
}
Compile the servlet and perform the same steps as described in the previous
section to test it.
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:
File : Description
AddCookie.html: Allows a user to specify a value for the cookie named MyCookie.
AddCookieServlet.java: Processes the submission of AddCookie.html.
GetCookiesServlet.java: Displays cookie values.

The HTML source code for AddCookie.html 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="http://localhost:8080/examples/servlets/servlet/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 {
// Get parameter from HTTP request.
String data = request.getParameter("data");
// Create cookie.
Cookie cookie = new Cookie("MyCookie", data);
Add cookie to HTTP response. response.addCookie(cookie);
Write output to browser. response.setContentType("text/html"); PrintWriter pw =
response.getWriter(); pw.println("<B>MyCookie has been set to"); pw.println(data);
pw.close();
}
}
The source code for GetCookiesServlet.java is shown in the following listing. It
invokes the getCookies( ) method to read any cookies that are included in the
HTTP GET request. The names and values of these cookies are then written to
the HTTP response. Observe that the getName( ) and getValue( ) methods are
called to obtain this information.

import java.io.*; import javax.servlet.*;


import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

Get cookies from header of HTTP request. Cookie[] cookies = request.getCookies();


Display these cookies. response.setContentType("text/html"); PrintWriter pw =
response.getWriter(); pw.println("<B>");
for(int i = 0; i < cookies.length; i++) { String name = cookies[i].getName(); String value =
cookies[i].getValue(); pw.println("name = " + name +
"; value = " + value);
}

pw.close();

}
}
Compile the servlets. Next, copy them to the appropriate directory, and update
the web.xml file, as previously described. Then, perform these steps to test this
example:

Start Tomcat, if it is not already running.


Display AddCookie.html in a browser.
Enter a value for MyCookie.
Submit the web page.

After completing these steps, you will observe that a feedback message is
displayed by the browser.
Next, request the following URL via the browser:
http://localhost:8080/examples/servlets/servlet/GetCookiesServlet
Observe that the name and value of the cookie are displayed in the browser.
In this example, an expiration date is not explicitly assigned to the cookie
via the setMaxAge( ) method of Cookie. Therefore, the cookie expires when the
browser session ends. You can experiment by using setMaxAge( ) and observe
that the cookie is then saved on the client machine.

Session Tracking
HTTP is a stateless protocol. Each request is independent of the previous one.
However, in some applications, it is necessary to save state information so that
information can be collected from 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. Session state is shared by all servlets that
are associated with a client.
The following servlet illustrates how to use session state.
The getSession() method gets the current session. A new session is created if one
does not already exist. The getAttribute( ) method is called to obtain the object
that is bound to the name "date". That object is a Date object that encapsulates
the date and time when this page was last accessed. (Of course, there is no such
binding when the page is first accessed.) A Date object encapsulating the current
date and time is then created. The setAttribute( ) method is called to bind the
name "date" to this object.
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 {
Get the HttpSession object.
HttpSession hs = request.getSession(true);
//Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter(); pw.print("<B>");
//Display date/time of last access.
Date date = (Date)hs.getAttribute("date"); if(date != null) {
pw.print("Last access: " + date + "<br>");
}
// Display current date/time.
date = new Date(); hs.setAttribute("date", date);
pw.println("Current date: " + date);
}
}
When you first request this servlet, the browser displays one line with the current
date and time information. On subsequent invocations, two lines are displayed.
The first line shows the date and time when the servlet was last accessed. The
second line shows the current date and time.

You might also like