O'Reilly logo

Java Extreme Programming Cookbook by Brian M. Coyner, Eric M. Burke

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

Testing Servlet Filters

Problem

You want to test servlet filters.

Solution

Write a FilterTestCase class and assert that the filter continues down the chain or that the filter causes the chain to break. A mock FilterChain needs to be written to simulate filter-chaining behavior, too.

Discussion

Filters were introduced in Version 2.3 of the Servlet specification, and allow for preprocessing of the request and post-processing of the response. Filters act like an interceptor, in that they are executed before and after the servlet is called. Some common uses of filters are to perform logging, ensure that a user is authenticated, add extra information to a response such as an HTML footer, etc.

Example 7-12 shows how to test a filter that ensures a user is authenticated with the server. If the user is not authenticated with the server, she is redirected to a login page. The next recipe talks about how to setup an authenticated user in Cactus.

Example 7-12. Security filter

package com.oreilly.javaxp.cactus.filter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.security.Principal; public class SecurityFilter implements Filter { public void init(FilterConfig config) { } public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { Principal principal = ((HttpServletRequest) req).getUserPrincipal( ); if (principal == null) { req.setAttribute("errorMessage", "You are not logged ...

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