Server side programs can be written using different server-side technologies , such as Common Gateway Interface (CGI) , Active Server Pages (ASP) and Servlets.
CGI scripts are written in C , C++ or perl programming languages .
In case of an application server using CGI script to process client request , the server creates a separate instance of the CGI script to process the request.
As a result, the efficiency of the server is affected when there is large number of concurrent requests.
2. Servlet Concept
Server side programs can be written using different server-side
technologies , such as Common Gateway Interface (CGI) , Active
Server Pages (ASP) and Servlets.
CGI scripts are written in C , C++ or perl programming languages
.
In case of an application server using CGI script to process client
request , the server creates a separate instance of the CGI script
to process the request.
As a result, the efficiency of the server is affected when there is
large number of concurrent requests.
3. ASP is a server –side technology that enables a developer to
combine both HTML and scripting language in the same page.
ASP objects are multithreading and can therefore concurrently
service multiple requests.
The limitation of the ASP is that it is not compatible with all the
commercial Web servers.
4. Servlets are server side programs written in Java.
Unlike CGI scripts ,the servlet initialization code is executed only
once.
Moreover , separate thread in the server handle each client-
request.
In addition, servlets inherit all the features of the Java
programming language.
5. Web containers
Web containers provide various services required by web
application , such as :
Managing various stages in the life cycle of the servlet, such as
initializing a servlet instance, processing the client request , and
removing the servlet instance from service.
Defining the security constraints that specifies only authorized
users can access the deployed servlets.
Managing database transactions when a servlet needs to read and
write data from a database , such as SQL Server 2000.
Creating and removing servlet instances from an instance pool
to serve multiple requests.
6. Tasks performed by the Web container
Loads the Servlet class
Instantiates the Servlet
Initializes the Servlet Instance
Passes Request to the Servlet
Instance
Sends Response
First Client Request
Request
Response
7. The Servlet Class Hierarchy
Servlet ServletConfig Serializable
GenericServlet
HttpServlet
UserDefinedServlet
Interfaces
Built-in
classes
User defines
class
8. The Servlet Life Cycle Methods
The javax.servlet.Servlet interface defines the life cycle methods
of the servlet such as init() , service() , and destroy().
The Web container invokes the init() , service(), and destroy()
methods of a servlet during its life cycle.
The sequence in which the Web container calls the life cycle
methods of a servlet is as follows :
9. 1. The Web container loads the servlet class and creates instance
of the servlet class.
2. The Web container invokes the init() method of the servlet
instance during initialization of the Servlet. The init() method
is invoked only once in the servlet life cycle .
3. The Web container invokes the service() method to allow a
servlet to process a client request.
4. The service() method processes the request and returns the
response back to the Web container.
5. The servlet then waits to receive and process subsequent
requests as explained in steps 3 and 4.
6. The Web container calls the destroy() method before removing
the servlet instance from the service. The destroy() method is
also invoked only once in the a servlet life cycle.
10. The init() method
The init() method is called during the initialization phase of the
servlet life cycle.
The Web container first maps the requested URL to the
corresponding servlet available in the Web container and then
instantiates the servlet.
The Web container then creates an object of the ServletConfig
interface, which contains the startup configuration information,
such as initialization parameters of the servlet.
The Web container then calls the init() method of the servlet and
passes the ServletConfig object to it.
11. The init() method ……..
The init() method throws a ServletException if the Web
container cannot initialize the servlet resources .
The servlet initialization completes before any client requests
are accepted.
The following code snippet shows the init() method:
public void init (ServletConfig config) throws ServletException
12. The service() Method
The service() method processes the client requests.
Each time the Web container receives a client request, it invokes the service()
method.
The service() method is invoked only after the initialization of the servlet is
complete.
When the Web container calls the service() method, it passes an object of the
ServletRequest interface and an object of the ServletResponse interface.
The ServletRequest object contains information about the service request
made by the client.
The ServletResponse object contains the information returned by the servlet
to the client.
13. The service() Method…….
The following code snippet shows the service() method:
public void service(ServletRequest req , ServletResponse res)
throws ServletException , IOException
The service() method dispatches a client request to one of the request handler
methods of the HttpServlet interface ,such as the doGet() , doPost() ,
doHead() , or doPut().
The request handler methods accepts the objects of the HttpServletRequest
and HttpServletResponse as parameters from the service() method.
service() method is not overridden in the HttpServlet as the Web container
automatically invokes the service() method.
The servlet functionality of the HTTP Servlets is written in doGet() or doPost()
methods.
14. The destroy() method
The destroy() method marks the end of the life cycle of a servlet.
The Web container calls the destroy() method before removing a servlet
instance from the service.
The Web container calls the destroy() method when :
1. The time period specified for the servlet has elapsed. The time period of
a servlet is the period for which the servlet is kept in the active state by the
Web container to service the client request.
2. The Web container needs to release servlet instances to conserve
memory.
3. The Web container is about to shut down.
15. The destroy() method……..
In the destroy() method you can write the code to release the
resources occupied by the servlet.
The following code snippet shows the code of the destroy()
method:
public void destroy();
16. Summary
The classes and interfaces , which are used to develop a servlet,
are packages in the javax.servlet and javax.servlet.http packages
of the Servlet API.
The javax.servlet.Servlet interface defines methods that are used
to manage the servlet life cycle.
The javax.servlet.ServletConfig interface is implemented by a
Web container to pass configuration information to the servlet.
The HttpServletRequest object represents a request sent by a
client using HTTP.
The HttpServletResponse object represents a response sent by a
servlet to a client using HTTP.
17. Assignment
Smart Software Developers wants to develop a web application
that will use servlets to display employee infromation stored in
the Employee table.
The application needs to have a user interface in which a user
can specify an employee id to view the data of the employee.
The interface should also display the number of times this site
has been visited.
Employee details are : Name , Address , Age , Designation.
18. The commonly used interfaces of javax.servlet package are :
1. ServletRequest Interface
2. ServletResponse Interface
3. ServletContext Interface
19. The ServletRequest Interface
The ServletRequest interface contains various methods to
handle client requests to access a servlet.
The following describes various methods of the ServletRequest
interface:
1. public String getParameter (String paramName)
-> Returns a String object that specifies the value of a particular
request parameter.
2. public String[] getParameterValues (String paramName)
-> Returns an array of String objects that contains all the values
of the request parameter.
20. 3. public Enumeration getParameterNames ()
-> Returns an Enumeration containing all the parameter
names as String objects that a servlet request contains.
4. public String getRemoteHost ()
-> Returns a String that specifies the full-qualified name of the
computer from which the request is sent.
5. public Sring getRemoteAddr ()
-> Returns a String that specifies the IP address of the
computer from which the request is sent.
21. The ServletResponse Interface
The ServletResponse interface contains various methods that
enable a servlet to respond to the client requests.
A servlet can send the response either as character or binary
data.
The PrintWriter stream can be used to send character data as
servlet response and ServletOutputStream stream to send to
binary data as servlet response.
The following describes various methods of the ServletResponse
interface:
22. 1. public ServletOutputStream getOutputstream()
throws IOException
-> Returns an object of the ServletOutputStream class that
represents an output stream to send binary data as response.
2. public PrintWriter getWriter () throws IOException
-> Returns an object of the PrintWriter class that servlet uses to
send character data as response.
3. public void setContentType(String type)
-> Sets the Multipurpose Internet Mail Extensions (MIME) type
for the servlet response. Some of the MIME types are text/plain
, image/jpeg , and text/html.
23. The ServletContext interface
The ServletContext interface provides information to servlets
regarding the environment in which they are running.
The context is also called as servlet context or Web context and is
created by the Web container as an object of the ServletContext
interface.
The Web container creates a ServletContext object for each
deployed Web application.
You can also use the ServletContext object to set attributes that
other servlet of your application can access.
The following describes various methods of the ServletContext
interface :
24. 1. public void setAttribute (String , Object)
-> binds the object with a name and stores the name/value pair as an
attribute of the ServletContext object .If an attribute already exists,
then this method replaces the existing attribute.
2. public Object getAttribute (String attrname)
-> Returns the object stored in the ServletContext object with the name
passed as a parameter.
3. public Enumeration getAttributeNames ()
-> Returns an Enumeration of String object that contain names of all
the context attributes.
4. public Enumeration getInitParameter (String pname)
-> Returns the value of the initialization parameter with the name
passed as a parameter.
25. 5. public Enumeration getInitParameterNames ()
-> Returns an Enumeration of String object that contain names
of all the initialization parameters.
6. public int getMajorVersion ()
-> Returns an integer value that specifies the major version of
the Servlet API that the Web container suports. If your Web
container support the version 2.4 of the Servlet API, this
method will return 2.
7. public int getMinorVersion()
-> Returns an integer value that specifies the minor version of the
Servlet API that the Web Container supports. If your Web
container supports the version 2.4 of the Servlet API , this
method will return 4.
26. The classes and interfaces of javax.servlet.http package handle
servlets that communicates using HTTP.
These servlets are also called as HTTP servlets.
The following are the commonly used interfaces of the
javax.servlet.http package:
1. HttpServletRequest Interface
2. HttpServletResponse Interface
3. HttpSession Interface
27. HttpServletRequest Interface
The HttpServletRequest interface extends the ServletRequest interface
to represent the request information being sent by an HTTP client.
HTTP requests have number of associated headers.
These headers provide extra information about the client ,such as the
name and version of browser sending the request.
Some of the important HTTP request headers are :
1. Accept: Specifies the MIME type that the client prefers to
accept.
2. Accept-Language : Specifies the language in which the
client prefers to receive the request.
3. User-Agent : Specifies the name and version of the browser
sending the request.
28. The following describes various methods of HttpservletRequest
1. public String getHeader (String fieldname)
-> Returns the value of the request header field ,such as Cache-
control and Accept-Langauge specified in parameter.
2. public Enumeration getHeaders (String sname)
-> Returns all the values associated with a specific request
haeader as an Enumeration of String objects.
3. public Enumeration getHeaderNames()
-> Returns the names of all the request headers that a servlet can
access as an Enumeration of the String Objects.
30. The HttpServletResponse interface
The HttpServletResponse interface extends the ServletResponse
interface and provides method to handle response, status
codes ,and response headers for servlets that communicates
using HTTP.
The following describes various methods of the
HttpServletResponse interface.
31. 1. void setHeader (String hname, String hvalue)
-> Sets the value of header , hname to hvalue. If the header has already
been set, the new value overwrites the existing value.
2. void setIntHeader (String hname ,int hvalue)
-> Sets the value of the header, hname to the int value, hvalue.
If the header has already been set , the new value overwrites the
existing value.
3. void setDateHeader (String hname,long datev)
->Sets the value of the header, hname with a long value datev. The
datev represents the number of milliseconds since the midnight of
January 1, 1970 , GMT.
32. 4. void addHeader (String hname , String hvalue)
-> Adds a header , hname with value , hvalue.This method adds a
new header if the header already exists.
5. void addIntHeader (String hname , int hvalue)
-> Adds a header , hname with an integer value , hvalue
6. void addDateHeader (String hname , long datev)
-> Adds a header named hname with value equal to given date ,
datev. The value of the datev must be in milliseconds , which
starts since midnight , January 1, 1970 , GMT.
33. 7. boolean containsHeader (String hname)
-> Returns true if the header , hname has already been set with a
specific value and false , if not.
8. void sendRediect (String url)
-> Redirects a request to the specified URL
34. The HttpSession Interface
The HttpSession interface contains methods to maintain the
state of an end user across a Web application.
An object of the HttpSession interface provides support for
tracking and managing the session of an end user.
The following describes various methods of the HttpSession
interface:
35. 1. public void setAttribute (String name, Object value)
-> Binds the object with a name and stores the name/value pair as an
attribute of the HttpSession object. If an attribute already exists , then
this method replaces the existing attribute.
2. public Object getAttribute(String name)
-> Retrieves the String object specified in the parameter ,from the
session object . If no object is found for the specified attribute , then
the getAttribute() method returns null.
3. public Enumeration getAttributeNames ()
-> Returns an Enumeration that contains the name of the all the objects
that are bound as attribute to the session object
36. Session Management
Session management is the process of keeping track of the
activities of a user across Web pages.
Consider an example of an online shopping mall.
The user can choose a product and add it to the shopping cart.
When the user moves to a different page , the details in the
shopping cart are still retained ,so that the user can check the
items in the shopping cart and then place the order.
37. Session Management Techniques
HTTP is a stateless protocol and therefore cannot store the
information about the user activities across Web pages.
However , there are certain techniques that helps store the user
information across Web pages using HTTP protocol.
The techniques that you can use to maintain the session
information are :
1. Hidden form field
2. URL rewriting
3. Cookies
4. Servlet session API
38. Hidden Form Field
You can use hidden form fields to maintain the session
information of a user while the user interacts with the web
application.
A hidden form field is embedded in an HTML page and is not
visible when viewed in a browser.
The following code snippet shows a hidden form field in an HTML
page :
<html>
<form method=“get” action=“ ”>
<input type=“hidden” name=“id” value=“L234”>
-------------
---------------
</html>
39. URL Rewriting
URL rewriting is a session management techniques that
manages user session by modifying a URL .
Usually ,this techniques is used when information that is to be
transferred is not very critical because the URL can be
intercepted easily during transfer.
For example , in an online shopping portal, servlet can modify a
URL to include user information , such as a username.
40. Using cookies
Cookies are small text files that are stored by an application server
in the client browser to keep track of all the users.
A cookie has values in the form of name/value pairs.
For example , a cookie can have a name , user with the value, Peace.
They are created by the server and are sent to the client with the
HTTP response headers.
The client saves the cookies in the local hard disk and sends them
along with the HTTP request headers to the server.
A Web browser is expected to support 20 cookies per host and the
size of each cookies can be a maximum of 4 bytes each.
41. Various characteristics of cookies are :
1. Cookies can only be read by the application server that had
written them in the client browser.
2. Cookies can be used by the server to find out the computer
name , IP address or any other details of the client computer by
retrieving the remote host address of the client where the
cookies are stored.
42. The Cookie class of javax.servlet.http package represents a
cookie.
The Cookie class provides a constructor that accepts the name
and value to create a cookie.
The following code snippet shows the constructor for creating a
cookie with name , cname , and value , cvalue:
public Cookie(String cname , String cvalue);
The HttpServletResponse interface provides the addCookie()
method to add a cookie to the response object, for sending it to
the client.
The following code snippet shows ho to add a cookie:
resp.addCookie(Cookie cookie);
43. The HttpServletRequest provides the getCookies() method that
returns an array of cookies that the request object contains.
The following code snippet shows how to retrieve cookies:
Cookie cookie [ ] = req.getCookies();
The Cookie class provides several methods to set and retrieve
various properties of a cookie.
The following describes the various methods of the Cookie class :
44. 1. public String getName()
-> Returns the name of the cookie.
2. public void setMaxAge(int expiry)
-> Sets the maximum time for which the client browser retains
the cookie value.
3. public int getMaxAge()
-> Returns the maximum age of the cookie in seconds.
4. public void setValue(String value)
-> Sets a new value to the cookie
5. public String getValue()
-> Returns the value of the cookie
45. An application server can store cookies in the client machine
only when the cookie are enabled in the client browser
46. Servlet Session API
You can use the classes and interfaces defined int the Servlet
Session API to create and manage user sessions.
Various interfaces provided by the Servlet Session API to create
and manage user session are ,
javax.servlet.http.httpSession
javax.servlet.http.HttpSessionListener , and
javax.servlet.http.HttpSessionBindingListener
47. The javax.servlet.http.HttpSession interface provides methods for
tracking the session of a user.
You can create an object of HttpSession interface to store session
information as name/value pairs.
You can later retrieve this information to manage user sessions.
The following describes the various methods defined in the
HttpSession interface.
48. 1. public void setAttribute (String name , Object value)
-> Binds an attribute to a session object with a unique name and stores
the name/value pair in the current session. If an object is already
bound with the same attribute, then the new object replaces the
existing.
2. public getAttribute(String name)
-> Retrieves the object bound with the attribute name specified in the
method , from the session object. If no object is found for the
specified attribute, then the getAttribute() method returns null.
3. public Enumeration getAttributeNames()
-> Returns the name of all the objects that are bound to the session
object.
49. 4. public void removeAttribute (String name)
-> Unbinds the session object from the attribute , name specified in the
method.
5. public void setMaxInactiveInterval (int interval)
-> Sets the maximum time for which the session will remain active. The
time is specified in seconds. If there is no client request during this
time , then the server invalidates the session. A negative value in this
method signifies that the session should always remain active.
6. public int getMaxInactiveInterval ()
-> Returns the maximum time in seconds for which the server will not
invalidate the session even if there is no client request.
50. 7. public String getId ()
->Returns a string that contains the unique identifier associated
with the session.
8. public void invalidate()
->Invalidates a session. All the objects bound to the session are
automatically unbound.
51. Assignment
Larry Williams is in charge of the garments section of Countryside
Markets. He receives information stating that the total in the bill is
wrong.
Larry visits the Web site of his company and does an online shopping.
He finds that the bill includes information of only those shirts that he
selected on the last Web page he visited. The information of shirts that
he selected in the earlier Web pages was lost.
Larry asks John, the developer of the company’s Web site , to modify
the Web site such that the shirts selected by a user should be tracked
and the bill should get updated accordingly.
John develops a test application for the customer, Mike to test the
functionality
52. Handling Errors and Exception in servlets
You can perform exception handling in a servlet to handle
exceptions thrown by the servlet.
You can also create customized error pages to display exceptions
and error messages and log these messages to the application
server log file.
53. Servlet Exceptions
The Servlet API defines two exception classes that are defined in
the javax.servlet package.
The two exceptions classes are ServletException and
UnavailableException.
The UnavailableException class is a subclass of the
ServletException
54. The javax.servlet.ServletException Class
The javax.servlet.ServletException class is defined in the
javax.servlet package and is subclass of the java.lang,Exception
class.
It defines a servlet exception that a servlet throws while
processing the client request.
This class contains the getRootCause () method , which returns
an object of type java,lang.Throwable that represents the root
cause of the exception
55. The javax.servlet.UnavailableException Class
The javax.servlet.UnavailableException exception class is thrown
by a servlet when the servlet is either temporarily or permanently
unavailable.
The methods provided by the UnavailableException class are :
1. public boolean isPermanent()
-> Returns a boolean value that describes whether a servlet is
permanently unavailable or not .If the servlet is permanently
unavailable , this method returns true.
2. public int getUnavailableSeconds ()
-> Returns the time , in seconds , for which the servlet will
remain unavailable
56. Handling Errors
Servlets in the Web application can generate errors and throws
exceptions.
You can provide information to users regarding these errors and
exception by sending errors messages and status codes that
represents various types of errors.
You can create customized error pages to format and display
information on the type of error and exception that occurs.
You can also log the error messages and the exceptions to the
web server log file to keep track of the errors and the exceptions
occurring in your Web application.
57. Error Messages and Status Codes
A status code is the information that the application server sends
to the client about the success or failure of a client request.
When the application server services a client request , it returns
the status code to the client browser through the response
object.
The HttpServletResponse of javax.servlet.http package defines
various fields that represent status codes.
You can these fields to send status codes from your servlet.
The status codes are logically grouped into following five
categories:
58. 1 . Information :
Information code group represent messages about the receipt
of a request and that the application server is processing the
request .
Some of the HttpServletResponse fields that represent
information codes are :
a] SC_SWITCHING_PROTOCOLS : Represents 101 status code and
indicates switching of protocols by the application server.
b] SC_CONTINUE : Represents 100 status code and indicates that the
client can continue its interaction with the application server.
59. 2. Success
Success code group represents a success message which indicates
that the request is successful .
Some of the HttpServletResponse fields that represent success
codes are :
a] SC_OK : Represents 200 status code and indicates that the request is
successfully received.
b] SC_ACCEPTED : Represents 202 status code and indicates that the
server has accepted the request and is processing the request.
60. 3. Redirection
Redirection code group represents a redirection message, which
indicates that the request is redirected to another page for
processing and service.
Some of the HttpServletResponse fields that represent redirection
codes are :
a] SC_MOVED_PERMANENTLY : Represents 301 status code and
indicates that the resource is moved permanently.
b] SC_MOVED_TEMPORARILY : Represents 302 status code and
indicates that the resource is moved temporarily.
61. 4. Client error
Client error code group represents a client error, which indicates
that the request has some error and cannot be serviced.
Some of the HttpServletResponse fields that represent client error
codes are :
a] SC_BAD_REQUEST : Represents 400 status code and indicates that the
syntax of the client request is not correct.
b] SC_NOT_FOUND : Represents 404 status code and indicates that the
resource requested by the client is not available.
c] SC_GONE : Represents 410 status code and indicates that the resource is
not available any longer.
62. 5. Server error
Server error code group represents a server error, which indicates
that the server is unable to fulfill the client request.
Some of the HttpServletResponse fields that represents server code
are :
a] SC_INTERNAL_SERVER_ERROR : Represents 500 status code and
indicates that there is an error in the server that prohibits it to fulfill the
request.
b] SC_NOT_IMPLEMENTED: Represents 501 status code and indicates
that the server does not provide the functionality to fulfill the request.
63. You can send an error response or status response to the client
whenever an error is generated during the processing of a Web
application.
The sendError() and setStatus() are the two methods of the
HttpServletResponse object that you can use to send error and
status messages to a client
64. The sendError() method
The sendError () method is defined in the HttpServletResponse.
You can use this method to send error messages to client.
The following describes the signatures of the overloaded
sendError () method:
a] public void sendError (int status)
-> Accepts an integer field of HttpServletResponse as argument that
describes the type of error that occurs and sends the error response to the
client.
b] public void sendError (int status , String message)
-> Accepts an additional String argument that describes the error and sends
the error response to the client.
The sendError () methods throws an exception , IllegalStateException if it is
called after a response is committted.
65. You can use the following code snippet to send an error messages to the client:
public void doPost (HttpServletRequest req , HttpServletResponse resp)
{
PrintWriter pw = null ;
try
{
pw = resp.getWriter();
pw.println(“This page is going to give an Error”);
resp.sendError(HttpServletResponse.SC_NOT_FOUND , “Sorry the source you
have requested is not available”);
} catch (Exception ex)
{
pw.println( ex.printStackTrace() ) ;
}
66. The setStatus () method
The setStatus () method defined in the HttpServletResponse ,
sets the status information about a servlet.
The following describes the signatures of the overloaded setStaus
() method:
a] public void setStatus (int status)
-> Accept an integer field of HttpServletResponse as argument that
represents the status information and sets the information to the response.
b] public void setStatus (int status, String message)
-> Accepts an additional String argument that describes the status of the
servelt.
The setStatus () method throws an exception, IllegalStateException , if it is called
after a response is committed.
67. You can use the following code snippet to use the setStaus () method to send an
error response to the client:
public void doPost(HttpServletRequest req , HttpServletResponse resp)
{
PrintWriter pw = null ;
try
{
pw = resp.getWriter ();
pw.println(“This page is going to display a status code”);
resp.setStatus (HttpServletResponse.SC_GONE);
} catch (Exception ex)
{
pw.println( ex.printStackTrace() );
}
}
68. Writing an Exception and Error to the Server Log File
You can log error massages and exceptions in the server log file
to keep a track of the kind of errors thrown by the application.
Logging the errors and exceptions helps you to identify the errors
that occur in you r Web application.
The ServletContext interface provides the log() method to log
error messages and exceptions.
You can use the following code to create a servlet that throws an
exception and logs the exception details in the server log file:
69. public class LogDemo extends HttpServlet
{
public void doGet (HttpServletRequest
req,HttpServletResponse resp) throws ServletException , IOException
{
ServletContext sc = getServletContext () ;
PrintWriter pw = resp.getWriter ();
pw.println(“<B>Writing an exception to the server log file</B>”);
try
{
int x = 9;
int y = x/0;
} catch (ArithmeticException ae)
{
sc.log(“dividing an intrger by zero will not give result”, ae);
}
}
} // server.log
70. Assignment
A user while using an online calculator applications enters a
non-numeric characters to adds the numbers.
When a servlet tries to convert the value entered by the user into
an integer type ,it throws an exception of type
NumberFormatException.
Create a Web Application that handles the exception using a
customized error page .
The customized error page needs to provide information on the
user and log the exception to the server log file.
71. Assignment
InfoSuper Corp . has created a dynamic Web site .
Whenever an error occurs , the stack trace displayed in the
browser is difficult to understand .
David Wong , the System Analyst of the company asks Don
Allen , the software programmer of the company to create a
customized error page .
Whenever an exception is thrown by a servlet , the servlet
dispatches the request to the customized error page.
The error page then displays the error in the browser is more
understandable format
72. Inter-Servlet Communication
In a Web application, various components of the application, such as servlet
might need to communicate with each other to process client requests.
For example, consider a servlet that displays copyright information of an
organization in a Web application.
You can you use various inter-servlet communication techniques to include
the contents of this servlet in all the other servlets of the application that need
to display the copyright information.
Similarly, a servlet in a web application can forward a request to another
servlet if any exception occurs while processing the request.
You can implement inter-servlet communication techniques in your Web
application in the following two ways:
1] Using Request Dispatcher
2] Using servlet Request Object
73. Request Dispatcher
A Request Dispatcher is an object of the javax.servlet.RequestDispatcher
interface that allows inter-servlet communication.
You can use Request Dispatcher in your servlet to forward a request to another
resource that can be a static page or another servlet.
You can also use the RequestDispatcher object to include the contents of
another resource in your servlet.
The ServletContext interface provides the getRequestDispatcher (String path)
method that returns the RequestDispatcher object.
The path argument of the method specifies the path relative to the context
root of the target resource.
Once you obtain the RequestDispatcher object, you canperform the following
two functions.
1] Include contents of another servlet
2] Forward request to another servlet.
74. Including Contents of Another Servlet
The RequestDispatcher interface provides the include () method
you can use to include the content of another servlet.
For this , you need to first obtain an object of RequestDispatcher
interface and then invoke the include () .
For example, consider the servlet , CopyrightServlet that displays
copyright information about ABC Inc., in the Web site of the
organisation.
75. import javax.servlet.*;
import javax.servlet.http.*;
Import java.io.*;
public class CopyrightServlet extends HttpSservlet
{
public void doGet (HttpServletRequest req , HttpServletResponse resp)
throws ServletException , IOException
{
PrintWriter pw = resp.getWriter ();
pw.println(“Copyright 2000-2004 ABC , Inc. All Rights Reserved.<br>”);
}
}
76. To include the contents of CopyrightServlet in the servlet ,
IncludeServlet , you need to first call the getRequestDispatcher()
method of the ServletContext interface by passing the path of
CopyrightServlet as a parameter.
This returns a RequestDispatcher object.
You can then call the include() method to include the content of
CopyrightServlet.
77. import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class IncludeServlet extends HttpServletp
{
public void doGet(HttpServletRequest req , HttpServletResponse resp)
throws ServletException , IOException
{
RequestDispatcher dispatch =
getServletContext().getRequestDispatcher(“/servlet/CopyrightServlet”);
PrintWriter pw = resp.getWriter ();
pw.println(“<b>The Copyright information included form copyright servlet
is:
<b><br>”);
/* Use the include () of RequestDispatcher to include the content */
dispatch.include (req , resp) ;
}
78. Forwarding Request to Other Servlets
You can use a RequestDispatcher objects to forward requests to
other servlets in your application.
For example , consider ABC , Inc. that provides tour packages for
vacations.
You need to create the Web site of ABC.. where users can
request for information, such as details of available flights ,
airport transfers , and hotel accommodations.
You can create a main servlet to process all these requests and
send back the responses.
79. However, doing this will increase the request processing time of the main
servlet.
Instead , you can develop different servlets to process specific client requests.
For example, the HotelInformation servlet can process the requests for hotel
accommodation while a FlightInformation servlet can process requests
pertaining to flight information.
The main servlet of the Web application can receive all requests of
corrresponding servlet.
The following code snippet shows how you can use RequestDispatcher in the
deGet() method to forward requests to different servlets of your application.
81. Using the Request Object
You have learned how the RequestDispatcher object allows inter-servlet
communications by forwarding request to another servlet and including
response from another servlet.
However , the RequestDispatcher objects does not allow servlets to share
data.
To share data between servlets, you can use the request object in your servlets
that needs to communicate.
82. You can use the setAttribute () method of the javax.servlet.ServletRequest
interface to set values of data in the request object.
Other servlets of the application can use the getAttribute () method of the
javax.servlet.ServletRequest interface to retrieve the value of the data.
For example , considers a Web application in which CalculatorServlet
performs arithmetic calculations.
Another servlet of the Web application will display the calculation result.
To send the calculated result to the second servlet , CalculatorServlet can
perform the following steps :
83. 1. Store the calculated data as attribute to the request object in the first
servlet.
2. Forward the request to the second servlet using RequestDispatcher.
The second servlet then retrieved the data form the request object and displays
the result.
You can use the following code to create the CalculatorServlet servlet that adds
two numbers specified by the user and stores the result as an attribute of
the request object.
The servlet then forwards the request to the DisplayServlet servlet:
84. Import java.io.*;
Import javax.servlet.*;
Import javax.servet.http.*;
public class CalculatorServlet extends HttpServlet
{
public void doGet (HttpServletRequest req , HttpServletReponse resp)
throws ServletException , IOExceptiion
{
int num1 = Interger.parseInt (req.getParameter (“number1”) ) ;
int num2 = Interger.parseInt (req.getParameter (“number2”) ) ;
int sum = num1 + num2 ;
req.setAttribute (“result” , new Integer(sum));
ServletContext contx = getServletConfig () . getServletContext() ;
RequestDispatcher disp = contx.getRequestDispatcher(“/servlet/DisplayServlet”);
disp.forward(req , resp);
}
}
85. public class DisplayServlet extends HttpServlet
{
public void doGet ( HttpServletRequest req , HttpServletResponse resp)
throws SevletException , IOException
{
Integer res = (Integer) req.getAttribute (“result”);
PrintWriter pw = rep.getWriter() ;
pw .println(“the result of the calculation is :” + res.toString() ) ;
}
}