O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.7. Mapping Requests to a Controller and Preserving Servlet Mappings

Problem

You want to map all requests to a single controller servlet, while preserving the servlet mappings for other servlets in a secure manner.

Solution

Use security-constraint elements in web.xml to prevent web users from making requests to the noncontroller servlets.

Discussion

What if the controller servlet that receives all requests wants to conditionally forward the request along to another servlet for specialized processing? If all of the other servlet mappings are removed from web.xml and the invoker-style URL pattern (/servlet/*) is mapped to the controller servlet itself, even the controller servlet is prevented from forwarding a request to another servlet! How can you get around these restrictions?

A solution is to retain the individual servlet mappings in web.xml. Then you can use security-constraint elements to prevent web users from making requests to these noncontroller servlets. When the controller servlet wants to forward a request to another servlet, it uses an object that implements the javax.servlet.RequestDispatcher interface. RequestDispatchers are not restricted from forwarding requests (using the RequestDispatcher.forward(request, response) method) to URL patterns that are specified by security-constraint elements. Example 3-10 shows a servlet named Controller that uses a RequestDispatcher to forward a request to another servlet.

Recipe 3.9 describes how to protect servlets from receiving ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required