Download presentation
Presentation is loading. Please wait.
Published byHannah Townsend Modified over 11 years ago
1
6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets
2
6-2 Copyright © 2005, Oracle. All rights reserved. Objectives After completing this lesson, you should be able to do the following: Use a cookie in a servlet Send HTTP headers to the client Use servlet filters Define event listeners
3
6-3 Copyright © 2005, Oracle. All rights reserved. Servlet Error handling Overview Client Web browser Request getCookies() getHeader() Response setHeader() addCookie()
4
6-4 Copyright © 2005, Oracle. All rights reserved. HTTP Headers Headers are HTTP details that are passed between the browser and the server. They can be response or request headers. The getHeader() method of HttpServletRequest retrieves the string value of the header. The setHeader() method of HttpServletResponse sends a header to the browser.
5
6-5 Copyright © 2005, Oracle. All rights reserved. Request Headers Additional request headers include the following: AcceptSpecifies MIME types that the browser supports Accept- Language Specifies the browsers preferred language CookieReturns cookies to servers that previously sent them to the browser RefererIndicates the URL of the referring Web page, for tracking users User-AgentIdentifies the browser that is making the request, for checking browser features
6
6-6 Copyright © 2005, Oracle. All rights reserved. Sending a Response There are three aspects to sending a response: Sending HTTP headers Sending a status code (an integer denoting the nature of response) Sending multimedia content
7
6-7 Copyright © 2005, Oracle. All rights reserved. Response Headers The HttpServletResponse class is used to send headers. You have seen an example of setting header information: setContentType("text/html");. Other headers are set by using the setHeader() method. Do not confuse HTTP headers with the HEAD tag in HTML pages.
8
6-8 Copyright © 2005, Oracle. All rights reserved. int pageVersion = Integer.parseInt(req.getParameter("pageVersion")); if (pageVersion >= currentVersion){ response.setStatus(response.SC_NO_CONTENT); }else{ //Send original page } Setting Status Codes If a servlet does not specify a status code, then the Web server sends the default status code (200). You can explicitly set a status code by using the setStatus() method. Example:
9
6-9 Copyright © 2005, Oracle. All rights reserved. public void doGet( HttpServletRequest req,HttpServletResponse res) throws IOException, ServletException{ String tempSite = this.randomSite(); // implementation not shown res.setStatus(res.SC_MOVED_TEMPORARILY); res.setHeader("Location", tempSite); } Example Assume that the randomSite() method generates a Web site randomly. For example, http://www233.oracle.com Requests to www.oracle.com can be sent to this site to provide load balancing.
10
6-10 Copyright © 2005, Oracle. All rights reserved. Sending Multimedia Content Multimedia content usually contains binary response data. Use the getOutputStream() method instead of the getWriter() method if you want to send binary data, such as images. Use the setContentType() method with the image/gif MIME type to send a GIF-encoded image. Use other MIME types to send other types of multimedia content.
11
6-11 Copyright © 2005, Oracle. All rights reserved.
12
6-12 Copyright © 2005, Oracle. All rights reserved. Cookies A cookie is a name or value pair sent by a servlet to a browser in the header. Cookies are persistent (the information sent is stored on the client, to be retrieved later). Cookies are often used to obtain state information, such as a username or preference.
13
6-13 Copyright © 2005, Oracle. All rights reserved. Cookie userCookie = new Cookie ("user", "fred"); userCookie.setMaxAge(60*60); //one hour response.addCookie(userCookie); Setting Cookies Use the Cookie() constructor to create a new cookie. Use the addCookie() method in the HttpServletResponse class to add and send the cookie to a browser.
14
6-14 Copyright © 2005, Oracle. All rights reserved. Retrieving Cookies Use the getCookies() method to fetch an array of Cookie objects. Cookie[] cookies = request.getCookies(); if (cookies != null) { String readValue; for (int i = 0; i < cookies.length; i++) readValue = cookies[i].getValue(); …
15
6-15 Copyright © 2005, Oracle. All rights reserved. About State Preservation Usually, the servlet engine instantiates the servlet only once. Any number of requests can be handled by the same instance of the servlet class. Values of any instance variable in the class persist between HTTP requests from multiple browsers. Values of variables in the doGet() or doPost() method do not persist between multiple browser requests.
16
6-16 Copyright © 2005, Oracle. All rights reserved. public class StateServlet extends HttpServlet { int counter = 0; //persistent variable public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{ res.setContentType("text/html"); PrintWriter out = res.getWriter(); String name = req.getParameter("firstName"); // name is transient variable out.println (" "); out.println ("Hello: " + name); out.println ("Hit count is: " + ++counter); out.println (" "); }} State Preservation: Example
17
6-17 Copyright © 2005, Oracle. All rights reserved. ServletContext The ServletContext interface defines the servlet within the Web application. Methods in ServletContext allow for retrieving the MIME type of a file, dispatching requests to other servlets, or writing to a log file.
18
6-18 Copyright © 2005, Oracle. All rights reserved. RequestDispatcher To forward the request to another servlet or JSP, use the RequestDispatcher interface: getServletContext().getRequestDispatcher(String url). RequestDispatcher contains two methods: forward() and include(). –Use the forward() method to transfer control to the associated URL. These methods take HttpServletRequest and HttpServletResponse as arguments.
19
6-19 Copyright © 2005, Oracle. All rights reserved. RequestDispatcher : Example public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("firstName"); if (name == null){ String url = "/loginerror.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); dispatcher.forward(request, response); else {out.println ("Hello: " + name) ;} }
20
6-20 Copyright © 2005, Oracle. All rights reserved. Servlet Filters Filters dynamically change the content or header of a request or response. A filter is used to: Intercept a request before a servlet is called Modify the request, response, and header values Optionally, customize the response
21
6-21 Copyright © 2005, Oracle. All rights reserved. Using Filters The javax.servlet.Filter interface is implemented to use a filter, and contains three methods: void init(FilterConfig) void doFilter(ServletRequest, ServletResponse, FilterChain) void destroy()
22
6-22 Copyright © 2005, Oracle. All rights reserved. doFilter() Method The doFilter() method: Examines the request header Modifies request headers by wrapping the request object Modifies the response by wrapping the response object Invokes the next filter in the filter chain
23
6-23 Copyright © 2005, Oracle. All rights reserved. Using Filters import javax.servlet.*; import javax.servlet.Filter; import java.io.*; public class HelloFilter implements Filter { private FilterConfig filterConfig; public void init(FilterConfig filterConfig){ System.out.println("Filter Initialized"); } public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("Hello from Filter"); chain.doFilter(request, response); } public void destroy(){} }
24
6-24 Copyright © 2005, Oracle. All rights reserved. Configuring Filters To use a servlet filter, the web.xml deployment descriptor is modified to include the tag: HelloFilter filterpackage.HelloFilter HelloFilter StateServlet
25
6-25 Copyright © 2005, Oracle. All rights reserved. Application Lifecycle Events Lifecycle Events are a new feature of the Servlet 2.3 API. Event listeners are used to check for state changes. There are two types of events: ServletContext and HttpSession. Event listeners can be notified when objects are initialized, destroyed, or when their attributes change.
26
6-26 Copyright © 2005, Oracle. All rights reserved. ServletContext Events Implement one or more ServletContext listener interfaces to respond to ServletContext events. The following methods are invoked when a ServletContext event occurs: contextInitialized() contextDestroyed() attributeAdded() attributeRemoved() attributeReplaced()
27
6-27 Copyright © 2005, Oracle. All rights reserved. HttpSession Events Implement one or more HttpSession listener interfaces to respond to HttpSession events. The following methods are invoked when an HttpSession event occurs: sessionCreated() sessionDestroyed() attributeAdded() attributeRemoved() attributeReplaced()
28
6-28 Copyright © 2005, Oracle. All rights reserved. Example of an Event Listener public class ConnectionManager implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { Connection conn = // create connection event.getServletContext().setAttribute("conn", conn); }
29
6-29 Copyright © 2005, Oracle. All rights reserved. Error Handling Java prevents a servlet from unintentionally or maliciously damaging the servlet engine. The Servlet API allows: –Logging of errors –Sending HTTP status codes to the client In the doGet() method, Java requires that any method that generates any exceptions must be handled explicitly. –You can let the servlet engine handle only IOException and ServletException, and not any other exceptions (for example, InterruptedException ).
30
6-30 Copyright © 2005, Oracle. All rights reserved. Summary In this lesson, you should have learned how to: Send headers and other content to the client Use filters to modify servlet response Handle state preservation Handle errors that might arise during the execution of your servlet
31
6-31 Copyright © 2005, Oracle. All rights reserved. Practices 6-1 and 6-2: Overview These practices cover the following topics: Creating a servlet that uses cookies Using servlet filters to manipulate headers
32
6-32 Copyright © 2005, Oracle. All rights reserved.
33
6-33 Copyright © 2005, Oracle. All rights reserved.
34
6-34 Copyright © 2005, Oracle. All rights reserved.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.