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.10. Giving Only the Controller Access to Certain Servlets

Problem

You want to set up the web application so that only a controller servlet has access to certain servlets.

Solution

Create a security-role that does not have any users mapped to it, then specify in the security-constraint element the servlets that you want to preserve for the controller.

Discussion

This recipe shows how you can create a security-constraint element that forbids any requests from reaching specified URL patterns.

The servlets mapped to those URL patterns are forwarded requests only from one or more controller servlets that use an object that implements the javax.servlet.RequestDispatcher interface. Recipe 3.7 includes an example controller servlet that forwards a request to another servlet using a RequestDispatcher. Example 3-17 shows how you can set up the security-constraint element for an example servlet with the registered name "Weather".

Example 3-17. A security-constraint that allows only RequestDispatcher.forward-related requests

<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-application_2_3.dtd"> <web-app> <!-- configure the Weather servlet; it receives requests from a controller servlet --> <servlet> <servlet-name>Weather</servlet-name> <servlet-class> com.jspservletcookbook.Weather </servlet-class> </servlet> <servlet-mapping> <servlet-name>Weather</servlet-name> <url-pattern>/weather</url-pattern> ...

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