1
Module 4Developing Servlets
Dev
elop
ing
Ser
vlet
s4
98 Ω Omega ΩDeveloping Applications for Java EE Platform
Describe the servlet API Use the request and response APIs Forward control and pass data Use the session management API
Objectives
2
Dev
elop
ing
Ser
vlet
s4
99 Ω Omega ΩDeveloping Applications for Java EE Platform
The servlet API provides the following facilities to servlets: Callback methods for initialization and request processing Methods by which the servlet can get configuration andenvironment information Access to protocol-specific resources
Basics of the Servlet API
Dev
elop
ing
Ser
vlet
s4
100 Ω Omega ΩDeveloping Applications for Java EE Platform
Structure of the Servlet API
3
Dev
elop
ing
Ser
vlet
s4
101 Ω Omega ΩDeveloping Applications for Java EE Platform
It is usually more convenient to work with the protocol-specific classes and interfaces for a number of reasons: Protocol-specific classes provide access to objects that areprotocol-specific, such as the HttpSessionimplementation. The method arguments and return values are defined in terms of other protocol-specific objects. Protocol-specific classes provide boilerplate processing for common operations.
Benefits of the Protocol-Specific API
Dev
elop
ing
Ser
vlet
s4
102 Ω Omega ΩDeveloping Applications for Java EE Platform
Benefits of extending the HttpServlet base class include: A simplified, no-argument init method, which can beoverridden to do initialization without the need to initializethe base class Standard handling of HTTPrequest types that are not ofinterest to the servlet Request handler arguments that are defined in terms ofHTTP-specific request and response objects
Benefits of the HttpServlet Class
4
Dev
elop
ing
Ser
vlet
s4
103 Ω Omega ΩDeveloping Applications for Java EE Platform
The service Method
Dev
elop
ing
Ser
vlet
s4
104 Ω Omega ΩDeveloping Applications for Java EE Platform
Request Handling Methods
5
Dev
elop
ing
Ser
vlet
s4
105 Ω Omega ΩDeveloping Applications for Java EE Platform
Basic Servlet
Dev
elop
ing
Ser
vlet
s4
106 Ω Omega ΩDeveloping Applications for Java EE Platform
Servlet ConfigurationWithout configuration, a servlet does not have an accessible URL.To configure a servlet and many other aspects of a web application, place a web.xml file in the WEB-INF directory.
6
Dev
elop
ing
Ser
vlet
s4
107 Ω Omega ΩDeveloping Applications for Java EE Platform
As outlined in the previous module, servlets are multi-threaded. A single servlet instance is created for each <servlet> configured in theweb.xml file. A servlet is instantiated sometime before itsservice method is called. A servlet can have two styles of initialization methods that are called before the service method and two types of methods called before discarding the servlet.
public void init() ....
@PostConstruct public void myInitMethod() ...
public void destroy() ...
@PreDestroy public void myDestroyMethod() ...
Servlet Life Cycle
Dev
elop
ing
Ser
vlet
s4
108 Ω Omega ΩDeveloping Applications for Java EE Platform
The servlet (web) container creates a request and response object for each new request. The request and response objects are passed to the servlet’sservice method. The request object:
• Provides information about the request• Allows the servlet to obtain user information and to
pass data to other web components The response object provides the servlet with mechanisms to generate a response or an error code to the browser.
Using the Request and Response APIs
7
Dev
elop
ing
Ser
vlet
s4
109 Ω Omega ΩDeveloping Applications for Java EE Platform
Request Object
Dev
elop
ing
Ser
vlet
s4
110 Ω Omega ΩDeveloping Applications for Java EE Platform
Response Object
8
Dev
elop
ing
Ser
vlet
s4
111 Ω Omega ΩDeveloping Applications for Java EE Platform
Example of Handling Form Data and
Producing Output
Dev
elop
ing
Ser
vlet
s4
112 Ω Omega ΩDeveloping Applications for Java EE Platform
Request processing and presentation are separated to simplifysoftware management. No component carries out both processing and presentation. The processing component typically completes the following actions: Does its work and gathers data to be rendered Puts the data into the request Transfers control to the presentation component with the use of a RequestDispatcher object
Forwarding Control and Passing Data
9
Dev
elop
ing
Ser
vlet
s4
113 Ω Omega ΩDeveloping Applications for Java EE Platform
A servlet has two ways to get access to an object that implements theRequestDispatcher interface: From the request, by URI as follows:
RequestDispatcher requestDispatcher =
request.getRequestDispatcher(“URI”);
From the servlet’s run-time context, by giving the name ofthe target servlet as defined in the deployment descriptor asfollows:
RequestDispatcher requestDispatcher =
getServletContext().getNamedDispatcher(“ServletName ”);
The RequestDispatcher Interface
Dev
elop
ing
Ser
vlet
s4
114 Ω Omega ΩDeveloping Applications for Java EE Platform
The argument to getRequestDispatcher is a URI, but it is interpreted by the web container with reference to the current application’s context. The URI must: Begin with a slash (/) Not contain a context root or be a full URI In the bank sample application, the servlet obtains the JSPcomponent to which it will transfer control using the following statement:
getRequestDispatcher (“/showCustomerDetails.jsp”);
The RequestDispatcher Target and the
Context Root
10
Dev
elop
ing
Ser
vlet
s4
115 Ω Omega ΩDeveloping Applications for Java EE Platform
The RequestDispatcher interface provides two methods totransfer control from a servlet (the calling component) to a target component:
• RequestDispatcher.forward – Typically used bycontrollers
• RequestDispatcher.include – Typically used byviews
Of these methods, forward is slightly faster but cannot merge the output of one component into the output of another.
The forward and include Methods
Dev
elop
ing
Ser
vlet
s4
116 Ω Omega ΩDeveloping Applications for Java EE Platform
The request object can carry data between components: In the calling component:
CustomerData customerData = // get customer data
request.setAttribute(“customerData”, customerData);
requestDispatcher.forward (request, response);
If the target component is a servlet:CustomerData customerData = (CustomerData)
getAttribute(“customerData”);
If the target component is a JSP component:<jsp:useBean id=”customerData”
class=”Bank.CustomerData” scope=”request”/>
Transfer of Data in the Request Object
11
Dev
elop
ing
Ser
vlet
s4
117 Ω Omega ΩDeveloping Applications for Java EE Platform
The Java EE platform’s session management model in the web tier is based on the HttpSession interface. A servlet can complete the following actions:
• Determine whether a session has just been created• Add a named item to the session• Retrieve a named item from the session• Close the session
Using the Session Management API
Dev
elop
ing
Ser
vlet
s4
118 Ω Omega ΩDeveloping Applications for Java EE Platform
Java EE Platform Web-Tier Session
Management Model
12
Dev
elop
ing
Ser
vlet
s4
119 Ω Omega ΩDeveloping Applications for Java EE Platform
Session and Authentication
Authentication and authorization services are provided by theServlet specification. Developers can implement a customprogrammatic solution.
• Programmatic solution – After a user has been authenticated, the user’s ID and authentication status typically become part of the session.
• Servlet Specification – The servlet can use therequest.getUserPrincipal method to get the user’s login identification instead of using the session.
Dev
elop
ing
Ser
vlet
s4
120 Ω Omega ΩDeveloping Applications for Java EE Platform
Session Binding
For each request, the server must be able to identify the specific browser to select the correct session object. This session binding is performed using cookies or URL rewriting.
13
Dev
elop
ing
Ser
vlet
s4
121 Ω Omega ΩDeveloping Applications for Java EE Platform
Session Timeout
The web container times out idle sessions after a period of inactivity. The web application:
• Must be developed to handle this situation gracefully,typically by reinitializing the session or redirecting back to a login page.
• Can set the timeout application wide in the web.xmldescriptor or on a per-session basis programmatically.
Dev
elop
ing
Ser
vlet
s4
122 Ω Omega ΩDeveloping Applications for Java EE Platform
New and Timed-Out Sessions
The request.getSession method always returns a session. TheHttpSession.isNew method returns truein either of the following situations:
• The session is a new session with a new browser.• The current browser session timed out before this
request.
14
Dev
elop
ing
Ser
vlet
s4
123 Ω Omega ΩDeveloping Applications for Java EE Platform
Retrieving a Session Object
Do not use the session object to transfer data between components in place of request attributes or method parameters. Sessions consume memory in the web server.
Dev
elop
ing
Ser
vlet
s4
124 Ω Omega ΩDeveloping Applications for Java EE Platform
Logout and Invalidation
Application design and session management can reduce the security risk and memory usage of sessions that remain open after use. Provide users with options for logging out or for closing the session:
• Log out after fixed number of steps• Log out with the click of a Logout button• Log out through menu operation
To close the session, call its invalidate method:if(“logout”.equals(request.getParameter(“action”))
session.invalidate();
Top Related