Learn Java for Web Development

(Tina Meador) #1
CHAPTER 2: Building Web Applications Using Servlets and JSP 65

You can get a RequestDispatcher in two ways.


   Getting a RequestDispatcher from a ServletRequest
 Getting a RequestDispatcher from a ServletContext

Getting a RequestDispatcher from a ServletRequest

RequestDispatcher view = request.getRequestDispatcher("bookDetails.jsp");


The getRequestDispatcher() method in ServletRequest takes a path for the resource to which
the request is being forwarded. If the path begins with a forward slash (/), it is considered by the
container to be starting from the root of the web application. If the path does not begin with the
forward slash, the container considers it relative to the original request.


Getting a RequestDispatcher from a ServletContext

RequestDispatcher view = getServletContext().getRequestDispatcher("/bookDetails.jsp");


The getRequestDispatcher() method takes a String path for the resource to which you are
forwarding the request. The RequestDispatcher, thus obtained from the context or request,
can be used to forward to the resource because the RequestDispatcher knows the resource
you are forwarding to, in other words, the resource that was passed as the argument to the
getRequestDispatcher(). Listing 2-8 illustrates calling forward on a RequestDispatcher.


Listing 2-8. Calling forward on RequestDispatcher


RequestDispatcher view = request.getRequestDispatcher("bookDetails.jsp");
view.forward(request, response);


Filters

A filter is a reusable Java component that can transform the content of HTTP requests, responses,
and header information. Filters are used for the following:


   Accessing static or dynamic content or modifying the request headers before
invoking a request
 Intercepting the invocation of a web component after the call is invoked

Figure 2-17. RequestDispatcher interface

Free download pdf