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.9. Restricting Requests for Certain Servlets

Problem

You want to allow only authenticated users to request certain servlets.

Solution

Use the security-constraint element in the web.xml deployment descriptor.

Discussion

Some web applications contain servlets that should not be invoked directly by web users, because they handle sensitive data and may have special jobs (such as administering the server or web application). For example, you could design a servlet that is accessed only by server administrators. How do you protect these servlets from being invoked improperly or by unauthorized users?

In the latter case, you can use declarative security , or container-managed security . This strategy involves configuring the web.xml deployment descriptor with your application's security information, thereby decoupling security information from your servlet's code. Any security changes for a web application can then be made in the XML configuration files (or via the WebLogic Server 7.0 Administration Console) without messing with the servlet's source code. The security configuration is then loaded and implemented by the servlet container.

You can also use programmatic security , which involves including security-related code within servlets, such as checking the HttpServletRequest object to see if a user is authorized to use a certain web resource.

For Tomcat, using the security-constraint element in web.xml requires creating a username and password in the XML file located at <Tomcat-installation-directory>/conf/tomcat-users.xml ...

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