Adding custom filter to filter chain in Spring

Posted on 15-01-2013 10:29 by graham
This tutorial shows how to you can add your own custom filter to the filter chain in Spring.

Business reason

I needed to add a filter that checks if some variable exists in the session before displaying a JSP page

The filter class

We'll start with creating a class that implements our filter:
public class SessionCheckFilter extends OncePerRequestFilter
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException
HttpSession session = req.getSession();

if (session != null)
Object user = req.getSession().getAttribute("user");

// do something with the user

chain.doFilter(req, res);

Adding the filter to the configuration

Now, let's make the filter accessible as a bean. In your applicationContext.xml file, add:
<bean name="sessionCheckFilterBean" class="com.wordgraphs.someapp.SecurityFilter" />

The next step is to put the filter into the filter chain so that it is called before any request. To do that, in your web.xml file add:

Then, where filters are put into the chain, add the following code to apply the filter to all requests matching the pattern *.jsp:

That's it! Your filter will be called before every JSP request.


Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems