Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

Module 1 Advanced Java Servlets

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Module 1 Advanced Java Servlets

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

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.

The Life Cycle of a Servlet

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.

Let us examine Create and Compile the Servlet Source Code


To begin, create a file named HelloServlet.java that contains the following program:

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 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 the core 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.

 Servlet interface declares life cycle methods for a servlet.


 ServletConfig interface allows servlets to get initialization parameters.
 ServletContext interface enables servlets to log events and access information about their
environment.
 ServletRequest interface used to read data from a client request.
 ServletResponse interface used to write data to a client response.

The following table summarizes the core classes that are provided in the javax.servlet
package:

 GenericServlet class implements the Servlet and ServletConfig interfaces.


 ServletInputStream class provides an input stream for reading requests from a client.
 ServletOutputStream class provides an output stream for writing responses to a client.
 ServletException class indicates a servlet error occurred.
 UnavailableException class indicates a servlet is unavailable

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
 void destroy( )
 String getServletInfo( )
 void init(ServletConfig sc) throws ServletException

void service(ServletRequest req, ServletResponse res) throws ServletException, IOException. 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, author, version, date, copyright). 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:

 ServletContext getServletContext( ) Returns the context for this servlet.


 String getInitParameter(String param) Returns the value of the initialization parameter
named param.
 Enumeration getInitParameterNames( ) Returns an enumeration of all initialization
parameter names.
 String getServletName( ) Returns the name of the invoking servlet.
The ServletContext Interface

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.

The ServletRequest Interface


The ServletRequest interface enables a servlet to obtain information about a client request.
Several of its methods are summarized

 getAttribute(String attr)
 getContentType( )
 getParameter(String pname)
 getParameterNames( )
 getParameterValues(String name)
 String getServerName( )

The ServletResponse Interface


The ServletResponse interface enables a servlet to formulate a response for a client. Several
of its methods are summarized
 getCharacterEncoding( ) returns the character encoding for the response.
 getOutputStream( )throws IOException returns a ServletOutputStream that can be used to
write binary data to the response.
 PrintWriter getWriter( ) throws IOException returns a PrintWriter that can be used to write
character data to the response.
 void setContentLength(int size) sets the content length for the response to size.
 void setContentType(String type) sets the content type for the response to type.

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 a 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. It defines the default constructor. In addition, a method is provided to read bytes
from the stream.

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. A default constructor is defined. 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. Aweb page is defined in PostParameters.htm, and a servlet is
defined in PostParametersServlet.java.

<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 source code for PostParametersServlet.java is shown in the following listing


import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParametersServlet
extends GenericServlet {
public void service(ServletRequest request, ServletResponse response) throws ServletException,
IOException {
PrintWriter pw = response.getWriter();
Enumeration e = request.getParameterNames();
while(e.hasMoreElements()) {
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
}
}

The javax.servlet.http Package


The javax.servlet.http package contains a number of interfaces and classes that are commonly
used by servlet developers. You will see that its functionality makes it easy to build servlets that
work with HTTP requests and responses. The following table summarizes the core interfaces that
are provided in this package:

 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.
 HttpSessionBindingListener informs an object that it is bound to or unbound from a
session.
The following table summarizes the core classes that are provided in this package. The most
important of these is HttpServlet. Servlet developers typically extend this class in order to
process HTTP requests.

 Cookie allows state information to be stored on a client machine.


 HttpServlet provides methods to handle HTTP requests and responses.
 HttpSessionEvent encapsulates a session-changed event.
 HttpSessionBindingEvent indicates when a listener is bound to or unbound from a session
value, or that a session attribute changed.

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.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();
}
}

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.htm, and a servlet is defined in ColorPostServlet.java.

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);
}
}

You might also like