1 / 30

Servlet API (Part II)

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

odette-bird
Download Presentation

Servlet API (Part II)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Servlet API (Part II) 4.1.02

  2. 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

  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. 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

  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. 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 } }

  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. 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

  11. 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 ...

  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. 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; }

  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. Request Dispatcher Flow forward Servlet A Servlet B Content returned to Browser include Servlet A Servlet B Content returned to Browser

  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. 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

  18. 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; } }

  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 • getServletContext() • .getRequestDispatcher("/pages/nav_bar.html") • .include(req, res); nav_bar.html Request Dispatcher

  20. 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>"); }

  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. 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"); ...}

  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. 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

  25. Servlet Objects (1 of 2) ServletRequest ServletResponse Client Sue ServletConfig Thread 1 ServletContext Thread 2 Client Bob Servlet A ServletRequest ServletResponse

  26. Servlet Objects (2 of 2) ServletRequest ServletResponse ServletConfig Client Sue Servlet A Thread 1 ServletContext Servlet B Thread 2 Client Bob ServletConfig ServletRequest ServletResponse

  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-8859-1 if none has been specified

  28. 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?

  29. 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.

  30. 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

More Related