6 copyright © 2005, oracle. all rights reserved. using advanced techniques in servlets

30
6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

Upload: hannah-townsend

Post on 27-Mar-2015

225 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

6Copyright © 2005, Oracle. All rights reserved.

Using Advanced Techniques in Servlets

Page 2: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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

Page 3: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

6-3 Copyright © 2005, Oracle. All rights reserved.

Servlet

Error handling

Overview

Client Web browser

Request

getCookies()getHeader()

Response

setHeader()addCookie()

Page 4: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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.

Page 5: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

6-5 Copyright © 2005, Oracle. All rights reserved.

Request Headers

Additional request headers include the following:

Accept Specifies MIME types that the browser supports

Accept-Language

Specifies the browser’s preferred language

Cookie Returns cookies to servers that previously sent them to the browser

Referer Indicates the URL of the referring Web page, for tracking users

User-Agent Identifies the browser that is making the request, for checking browser features

Page 6: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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

Page 7: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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.

Page 8: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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:

Page 9: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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.

Page 10: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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.

Page 11: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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.

Page 12: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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.

Page 13: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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();…

Page 14: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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.

Page 15: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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 ("<html><body>"); out.println ("Hello: " + name); out.println ("Hit count is: " + ++counter); out.println ("</body></html>"); }}

State Preservation: Example

Page 16: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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.

Page 17: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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.

Page 18: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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

Page 19: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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

Page 20: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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()

Page 21: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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

Page 22: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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(){}}

Page 23: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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 <filter> tag:

<filter>

<filter-name>HelloFilter</filter-name>

<filter-class>filterpackage.HelloFilter

</filter-class>

</filter>

<filter-mapping>

<filter-name>HelloFilter</filter-name>

<servlet-name>StateServlet</servlet-name>

</filter-mapping>

Page 24: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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.

Page 25: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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()

Page 26: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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()

Page 27: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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);

}

Page 28: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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

Page 29: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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

Page 30: 6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets

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