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 ...

Get Java Extreme Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.