HTTP Session handling using Servlet Filters

package com.javahunter.taher.filter;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SessionFilter implements Filter {
    private ArrayList<String> urlList;
    public void destroy() {
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String url = request.getServletPath();
        boolean allowedRequest = false;
        if(urlList.contains(url)) {
            allowedRequest = true;
        if (!allowedRequest) {
            HttpSession session = request.getSession(false);
            if (null == session) {
        chain.doFilter(req, res);
    public void init(FilterConfig config) throws ServletException {
        String urls = config.getInitParameter("avoid-urls");
        StringTokenizer token = new StringTokenizer(urls, ",");
        urlList = new ArrayList<String>();
        while (token.hasMoreTokens()) {

To be added to web.xml

This entry was posted in JSP, Servlet. Bookmark the permalink.

One Response to HTTP Session handling using Servlet Filters

  1. vikas says:

    hello sir,
    Thanx for such a nice tutorial .will u plz guide me how to use this filter inside my app
    and what to write in url mapping in web.xml

    Any suggestion will be heartely appreciated…..Thank you Sir….

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s