servlet api (part ii)
DESCRIPTION
Servlet API (Part II). 4.1.02. Unit objectives. After completing this unit, you should be able to: Discuss servlets as controllers (Model-View-Controller architecture) Look at the processing of request and response headers Understand how servlets handle redirection Discuss object sharing - PowerPoint PPT PresentationTRANSCRIPT
®
IBM Software Group
© 2007 IBM Corporation
Servlet API (Part II)
4.1.02
2
After completing this unit, you should be able to: Discuss servlets as controllers (Model-View-Controller
architecture) Look at the processing of request and response headers Understand how servlets handle redirection Discuss object sharing Look at how servlets can forward to or include content from
other servlets Understand the requirements for special characters in HTML
documents Discuss multithreading and thread safety issues Describe some of the internationalization support for servlets Understand the use of and need for the servlet context
After completing this unit, you should be able to: Discuss servlets as controllers (Model-View-Controller
architecture) Look at the processing of request and response headers Understand how servlets handle redirection Discuss object sharing Look at how servlets can forward to or include content from
other servlets Understand the requirements for special characters in HTML
documents Discuss multithreading and thread safety issues Describe some of the internationalization support for servlets Understand the use of and need for the servlet context
Unit objectives
3
Overview of Model-View-Controller (MVC) Servlet-only applications – servlet acts as model, view, and
controllerPoor separation of concerns
Servlet and JavaServer Pages (JSP) applications – the servlet is the controller, the JSP page is responsible for presentation, and other Java classes are the modelServlets (controller)JSP page (view)Business logic (model)
JavaBeans Enterprise JavaBeans (EJBs)
4
Display Page (JSP)
Request
Response
Fo
rward
Interaction Controller
(Servlet, JSP)
Enterprise Logic and
Data
Enterprise Servers
Third-tier PlatformsApplication Server
Browser
Model-View-Controller (MVC)
5
Controller Organization The Controller establishes the overall control flow in response
to a request At the highest level, the controller must:
Perform precondition checks Delegate business tasksEstablish state management tasks
The delegate business tasks step typically involves:Location of appropriate business objectsDelegate computation to business objectsBased on responses, select response agent
6
Processing Request Headers The request header is built by the Web browser and sent to the
Web server The servlet accesses the request header values from the
HttpServletRequest object passed to the doGet or doPost methods
Headers supported differ based on HTTP levelHTTP 1.1 headers are a superset of HTTP 1.0 headersQuery the HTTP level via the
HttpServletRequest.getProtocol method Returns HTTP/1.1 for HTTP 1.1
There are HttpServletRequest methods for standard headersThe getHeaders and getHeaderNames methods return
Enumeration objects which provide access to all the header values associated with a particular header name
The getHeader method returns the first (or only) value for the named header
7
Common Headers and HttpServletRequest Methods
Input data type and lengthHeaders: Content-type and Content-length Methods: getContentType and getContentLength
CookiesHeader: CookieMethod: getCookies
Identification for authorization purposesHeader: AuthorizationMethods: getAuthType and getRemoteUser
ProtocolMethod: getMethod
8
// called by doGet and doPost methods to process requestprivate void processRequest( HttpServletRequest request, HttpServletResponse response) throws ... { ... // input parameters have been processed String method = request.getMethod(); if (method.equals("GET")) { // special "GET" processing String lang = request.getHeader("Accept-Language"); // lang has the client's language // now set the status and resp. headers // and build the output document
}}
Processing Request Headers (Example)
9
Setting the Response Headers Can be set via the HttpServletResponse methods
setHeader, setDateHeader, and setIntHeader method.Some headers have their own methods: setContentType,
setContentLength, addCookie and sendRedirect
Response headers are required for some status codes:Document-moved status codes (range 300 to 307) require
a Location headerStatus code of 401 must have an associated WWW-
Authenticate header
Add additional support for your servlet.Cache-Control (HTTP 1.1) and Pragma (HTTP 1.0) -
cache optionsRefresh - how soon (in seconds) the browser should ask for
an updated page
10
Main type / subtype Document type
application/pdf Acrobat file (.PDF)
application/postscript PostScript file
application/vnd.lotus-notes Lotus Notes file
application/x-gzip Gzip archive
application/x-java-archive JAR file
application/zip Zip Archive
audio/x-wav Windows sound file
text/html HTML document
text/xml XML document
image/gif GIF image
Content-Type The Content-Type header is set via the setContentType
method of the HttpServletResponse object Specifies the Multipurpose Internet Mail Extension (MIME)
type of the returned document Form is main_type/sub_type
11
// process input parms and request headers...// set the return valueresponse.setStatus(HttpServletResponse.SC_OK);
// set the document typeresponse.setContentType("text/html");
// turn off cachingif (request.getProtocol().equals("HTTP/1.0")) {
// HTTP 1.0response.setHeader("Pragma","no-cache");
} else {// HTTP 1.1 or laterresponse.setHeader("Cache-Control","no-cache");
}response.setDateHeader("Expires", 0);// build the output document...
Response Header (Example)
12
Response Redirection and Error Sending Response Redirect: sendRedirect()
Sends redirection response to client URL specifies the redirection location
May be absolute or relative
Error Sending: sendError() Sets a response status codeServer-specific error page describing the error sent as
responseCustom pages may be defined for specific codes in Web
deployment descriptor
13
private void processRequest( HttpServletRequest request, HttpServletResponse response) ... { // process request headers & query data ... // redirect to another URL String url = "/YourResults.html"; if (test.equals("Error")) response.sendError(HttpServletResponse.SC_BAD_REQUEST); else response.sendRedirect (response.encodeRedirectURL(url)); return;}
Redirection and Send Error (Example)
14
Request Dispatcher The RequestDispatcher allows you to forward a request to
another servlet or to include the output from another servlet Used to support both forwarding processing to and including
response from a variety of local Web resourcesFor example, JSP pages and HTML files
If a reference to the RequestDispatcher is acquired from the ServletContextPath information is relative to the ServletContext
If a reference to the RequestDispatcher is acquired from the HttpServletRequestPath information is relative to the path of the current request
15
ServletA
ServletB
Content returned to Browser
forward
Content returned to Browser
include
Request Dispatcher Flow
ServletA
ServletB
16
Sample Use of Request Dispatcher Forward to a JSP
getServletContext().
getRequestDispatcher("/pages/showBalance.jsp").
forward(request, response);
Include static HTML
getServletContext().
getRequestDispatcher("/pages/navigation_bar.html").include(request, response);
17
Involving other Resources: Forwarding To have another resource build the response, use the
RequestDispatcher's forward method getRequestDispatcher(resourceName).
forward(request,response)
IllegalStateException is thrown if the source servlet accesses the ServletOutputStream or PrintWriter object
Request Dispatcher
showBalance.jsp
getServletContext() .getRequestDispatcher("/pages/showBalance.jsp")
.forward(request, response);
18
private void processRequest( HttpServletRequest request, HttpServletResponse response) ... { // process request headers & query data ... // Forward the request if (errorFound) { String res = "/ErrorFound.html"; getServletContext().getRequestDispatcher(res). forward(request, response); return; }}
Forward Method (Example)
19
Involving other Resources: Including To have another resource be included in the response, use the
RequestDispatcher's include method
getRequestDispatcher(resourceName).include(request,response)
The target resource should not set the response headers. If attempted, there is no guarantee that the target values will be used
nav_bar.html
getServletContext() .getRequestDispatcher("/pages/nav_bar.html") .include(req, res); Request
Dispatcher
20
private void processRequest( HttpServletRequest request, HttpServletResponse response) ... { // process request headers & query data ... // include the request response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML><BODY>Start of INCLUDED request"); out.println("<P>Hi " + request.getParameter("name")); out.flush(); getServletContext().getRequestDispatcher(
"/ILSCS01/DispatcherInclude").include(request, response);
out.println("<P>End of request</BODY></HTML>");}
Include Method (Example)
21
Sharing Objects There are several ways to share objects between servlets and
JSPs:ServletContext
getServletContext().setAttribute("objectName",anObject);
getServletContext().getAttribute("objectName");
HttpServletRequest
request.setAttribute("objectName",anObject);
request.getAttribute("objectName");
22
HttpServletRequest
"CUSTOMER"Customer
Sharing Objects Example
// Servlet "A"public void doGet (HttpServletRequest request, HttpServletResponse resp)... { // process request headers & query data Customer cust; ... request.setAttribute("CUSTOMER", cust); String res = "/Internal/ServletB"; getServletContext().getRequestDispatcher(res).forward(request, resp);}
// Servlet "B"public void doGet (HttpServletRequest req, HttpServletResponse resp) ... { Customer aCust = (Customer) req.getAttribute("CUSTOMER");...}
getAttribute()
1
2
setAttribute()
23
Servlet Context A Servlet Context defines a group of related servlets
Allows for relative pathsRooted at a particular point in the URI namespaceScope for data sharing among servlets
Programmatically accessed via javax.servlet.ServletContext Servlet Context Attributes
Allows for simple application scoped data sharing between servlets
getAttribute() and setAttribute() methods ServletContext.getResource
Allows a servlet to load resources specified via a relative path without assuming an absolute directory structure on the server
24
www.hotel.ibm.com
/Rooms/HRApps/Personnel
/Hire /DisplayRooms/Login/Retire
ServletContext
/HRApps/Personnel
ServletContext/Rooms
Web container
servlet
Web Containers and Servlet Context
25
Client Sue
Client Bob
ServletRequestServletResponse
ServletConfig
ServletContext
ServletResponseServletRequest
Thread 1
Thread 2
Servlet A
Servlet Objects (1 of 2)
26
Client Sue
Client Bob
ServletRequestServletResponse
ServletConfig
ServletContext
ServletResponseServletRequest
Servlet AThread 1
Servlet BThread 2
ServletConfig
Servlet Objects (2 of 2)
27
Internationalization Accepting Locale
Communicated from the client using the Accept-Language header
Use getLocale() and getLocales() methods of the ServletRequest interface to get the locales client will accept content in
Setting LocaleUse setLocale() method of the ServletResponse interface
to set the language attributes of a responsesetLocale() method should be called before the getWriter()
method of the ServletResponse interface is called Default encoding of a response is ISO-8859-1 if none has
been specified
28
Checkpoint
1. How do you forward a request to another servlet?2. How can you pass an object to a servlet you are forwarding
to?3. How can you include dynamic content generated by
another servlet?4. What is the servlet context?5. What servlets share a servlet context?
29
Checkpoint solutions
1. Use the request dispatcher to invoke the target servlet:getServletContext().getRequestDispatcher
(“/servlet/MyServlet”).forward(req, res);
2. Set the object as an attribute to the HttpServletRequest. The target servlet can then getAttribute() and cast it to the proper type. You call also use the session or the servlet context.
3. Use an include() to temporarily give control to another servlet.
4. The servlet context is an execution context of a group of related servlets. It allows for the servlets to use relative paths to refer to each other, and provides another way to share objects between servlets. Servlets within the same servlet context are defined in the same Web application.
5. Servlets defined within the same Web application share a servlet context.
30
Having completed this unit, you should be able to: Discuss servlets as controllers (Model-View-Controller
architecture) Look at the processing of request and response headers Understand how servlets handle redirection Discuss object sharing Look at how servlets can forward to or include content from
other servlets Understand the requirements for special characters in HTML
documents Discuss multithreading and thread safety issues Describe some of the internationalization support for servlets Understand the use of and need for the servlet context
Having completed this unit, you should be able to: Discuss servlets as controllers (Model-View-Controller
architecture) Look at the processing of request and response headers Understand how servlets handle redirection Discuss object sharing Look at how servlets can forward to or include content from
other servlets Understand the requirements for special characters in HTML
documents Discuss multithreading and thread safety issues Describe some of the internationalization support for servlets Understand the use of and need for the servlet context
Unit summary