® IBM Software Group © 2007 IBM Corporation Servlet API (Part II)
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 controller Poor 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 model Servlets (controller) JSP page (view) Business logic (model) JavaBeans Enterprise JavaBeans (EJBs)
4 Display Page (JSP) Request Response Forward Interaction Controller (Servlet, JSP) Enterprise Logic and Data Enterprise Servers Third-tier Platforms Application 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 tasks Establish state management tasks The delegate business tasks step typically involves: Location of appropriate business objects Delegate computation to business objects Based 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 level HTTP 1.1 headers are a superset of HTTP 1.0 headers Query the HTTP level via the HttpServletRequest.getProtocol method Returns HTTP/1.1 for HTTP 1.1 There are HttpServletRequest methods for standard headers The 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 length Headers: Content-type and Content-length Methods: getContentType and getContentLength Cookies Header: Cookie Method: getCookies Identification for authorization purposes Header: Authorization Methods: getAuthType and getRemoteUser Protocol Method: getMethod
8 // called by doGet and doPost methods to process request private 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 header Status 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 options Refresh - how soon (in seconds) the browser should ask for an updated page
10 Main type / subtypeDocument type application/pdfAcrobat file (.PDF) application/postscriptPostScript file application/vnd.lotus-notesLotus Notes file application/x-gzipGzip archive application/x-java-archiveJAR file application/zipZip Archive audio/x-wavWindows sound file text/htmlHTML document text/xmlXML document image/gifGIF 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 value response.setStatus(HttpServletResponse.SC_OK); // set the document type response.setContentType("text/html"); // turn off caching if (request.getProtocol().equals("HTTP/1.0")) { // HTTP 1.0 response.setHeader("Pragma","no-cache"); } else { // HTTP 1.1 or later response.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 code Server-specific error page describing the error sent as response Custom 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 resources For example, JSP pages and HTML files If a reference to the RequestDispatcher is acquired from the ServletContext Path information is relative to the ServletContext If a reference to the RequestDispatcher is acquired from the HttpServletRequest Path information is relative to the path of the current request
15 Servlet A Servlet B Content returned to Browser forward Content returned to Browser include Request Dispatcher Flow Servlet A Servlet B
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").i nclude(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(" Start of INCLUDED request"); out.println(" Hi " + request.getParameter("name")); out.flush(); getServletContext().getRequestDispatcher( "/ILSCS01/DispatcherInclude"). include(request, response); out.println(" End of request "); } 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() 12 setAttribute()
23 Servlet Context A Servlet Context defines a group of related servlets Allows for relative paths Rooted at a particular point in the URI namespace Scope 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 /Rooms /HRApps/Personnel /Hire /DisplayRooms /Login /Retire Servlet Context /HRApps/Personnel Servlet Context /Rooms Web container servlet Web Containers and Servlet Context
25 Client Sue Client Bob ServletRequest ServletResponse ServletConfig ServletContext ServletResponse ServletRequest Thread 1 Thread 2 Servlet A Servlet Objects (1 of 2)
26 Client Sue Client Bob ServletRequest ServletResponse ServletConfig ServletContext ServletResponse ServletRequest Servlet A Thread 1 Servlet B Thread 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 Locale Use setLocale() method of the ServletResponse interface to set the language attributes of a response setLocale() method should be called before the getWriter() method of the ServletResponse interface is called Default encoding of a response is ISO 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