MadJlzz MadJlzz - 9 months ago 39
Java Question

Possible misunderstanding of the doFilter method

I am actually pretty new to the Java EE specifications since I am kind of young. I never learned this things at school and I am facing a weird behaviour with the


Consider the following filter :

@WebFilter(filterName = "URLFilter", value = "/test")
public class URLFilter implements Filter {

public void destroy() {}

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletResponse response = (HttpServletResponse) resp;

if (response.getStatus() == HttpServletResponse.SC_NOT_FOUND)

chain.doFilter(req, resp);

public void init(FilterConfig config) throws ServletException {}


There is no servlet or page present in
and in my browser, the status is obviously a
404 not found
error when accessing the URL and so should be the value returned to me by the
method which isn't. (actually having a
status code)

Why is my filter not redirecting me to
as requested ? Do I misunderstand the use of
in general ?


My question was about redirecting the client (using the
) when a page is not found. I did not understand the filter part because I didn't know that
are actually filled with the new data when
is called. (which I actually found strange since the doFilter is calling the next Filter chained by the COR pattern)

I've made a class inheriting the
, implemented it, passed it to the Filter and it's working fine now.

Answer Source

Your filter is invoked before trying to access the actual resource (servlet, page, file, whatever) located at /test. So the response status can't be 404 yet at this time.

Then your filter invokes chain.doFilter(), thus telling the container to actually serve the resource at /test. Since there is no such resource, you get a 404.