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

11.11. Using a Filter to Monitor Session Attributes

Problem

You want to use a filter to check a session attribute prior to the request reaching a servlet.

Solution

Create a Java class that implements javax.servlet.Filter, write session-related code in the class's doFilter( ) method, then configure the filter in your deployment descriptor.

Discussion

Filters, as their name suggests, are semipermeable barriers through which requests to your web application must pass before they reach servlets, JSPs, or even static content. Filters are technically Java classes that implement the javax.servlet.Filter interface. A filter can have a look at the ServletRequest and ServletResponse objects before these objects find their way to a servlet's service methods (which include service( ), doGet( ), and doPost( )). Filters can initiate authentication, logging, encryption, database actions, caching, and just about any other task that passes through request and response objects.

Filters are configured in web.xml. In Example 11-18, a filter checks a logged-in HttpSession attribute, and logs its activities by calling the ServletContext object's log( ) method. This filter is mapped to a servlet registered in web.xml as MyServlet. Any requests to the MyServlet servlet cause the SessionFilter.doFilter( ) method to be called. Example 11-17 shows the relevant entries in web.xml .

Example 11-17. Configuring a filter in web.xml

<!-- the beginning of web.xml goes here --> <filter> <filter-name>SessionFilter</filter-name> ...

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