300 likes | 391 Views
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
E N D
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 • 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
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)
Model-View-Controller (MVC) Interaction Controller (Servlet, JSP) Enterprise Servers Request Enterprise Logic and Data Forward Response Display Page (JSP) Browser Third-tier Platforms Application Server
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
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
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
Processing Request Headers (Example) // 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 } }
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
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 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
Response Header (Example) // 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 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
Redirection and Send Error (Example) 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; }
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
Request Dispatcher Flow forward Servlet A Servlet B Content returned to Browser include Servlet A Servlet B Content returned to Browser
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);
Request Dispatcher 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 • getServletContext() • .getRequestDispatcher("/pages/showBalance.jsp") • .forward(request, response); showBalance.jsp
Forward Method (Example) 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; } }
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 • getServletContext() • .getRequestDispatcher("/pages/nav_bar.html") • .include(req, res); nav_bar.html Request Dispatcher
Include Method (Example) 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>"); }
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");
1 2 getAttribute() 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); } setAttribute() "CUSTOMER" Customer HttpServletRequest // Servlet "B" public void doGet (HttpServletRequest req, HttpServletResponse resp) ... { Customer aCust = (Customer) req.getAttribute("CUSTOMER"); ...}
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
Web Containers and Servlet Context www.hotel.ibm.com Web container /Rooms /HRApps/Personnel /Hire /Retire /Login /DisplayRooms servlet Servlet Context /Rooms Servlet Context /HRApps/Personnel
Servlet Objects (1 of 2) ServletRequest ServletResponse Client Sue ServletConfig Thread 1 ServletContext Thread 2 Client Bob Servlet A ServletRequest ServletResponse
Servlet Objects (2 of 2) ServletRequest ServletResponse ServletConfig Client Sue Servlet A Thread 1 ServletContext Servlet B Thread 2 Client Bob ServletConfig ServletRequest ServletResponse
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-8859-1 if none has been specified
Checkpoint • How do you forward a request to another servlet? • How can you pass an object to a servlet you are forwarding to? • How can you include dynamic content generated by another servlet? • What is the servlet context? • What servlets share a servlet context?
Checkpoint solutions • Use the request dispatcher to invoke the target servlet: getServletContext().getRequestDispatcher (“/servlet/MyServlet”).forward(req, res); • 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. • Use an include() to temporarily give control to another servlet. • 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. • Servlets defined within the same Web application share a servlet context.
Unit summary 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