Filter not working

Refresh

March 2019

Views

1.4k time

1

I basically have a filter and in it's doFilter method, i'm just printing a message to console and i have applied that filter to every page of my sample web app.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">


<filter>
    <filter-name>LoginFilter</filter-name>
    <filter-class>
        com.mypkg.filters.LoginFilter
    </filter-class>
</filter>
<filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<welcome-file-list>
<welcome-file>utility.jsp</welcome-file>

and my filter code LoginFilter.java

package com.mypkg.filters;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
//other imports

public class LoginFilter implements Filter {

@Override
public void init(FilterConfig config) throws ServletException {
     System.out.println("Filter init ran!");
}

@Override
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
    System.out.println("Filter running!");
}

@Override
public void destroy(FilterConfig config) throws ServletException {
     //System.out.println("Filter destoryed!");
}

Now when i first ran this filter, i got "Filter running" message but after that i included hibernate and other libraries, it stopped working, i removed them and same result. Filter doesn't run. Checked url pattern and everything.. Clueless!!

Any pointers?

2 answers

1

First of all, in you doFilter method you should call the next filter in the chain:

chain.doFilter(request, response);

Without this your request will not be processed further after your filter.

This can be a reason of your problem.

EDIT:

Also your destroy() method is wrong. Here how you should rewrite it:

@Override
public void destroy() {
     System.out.println("Filter destoryed!");
}
1

Maybe you have another Filter executed before yours, that does not call chain.doFilter(), thus preventing next filters (including yours) to be executed.