MadJlzz MadJlzz - 1 month ago 6
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

doFilter
method.

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)
response.sendRedirect("/");

chain.doFilter(req, resp);
}

public void init(FilterConfig config) throws ServletException {}

}


There is no servlet or page present in
/test
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
getStatus()
method which isn't. (actually having a
200
status code)

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

UPDATE:

My question was about redirecting the client (using the
sendRedirect()
) when a page is not found. I did not understand the filter part because I didn't know that
resp
and
req
are actually filled with the new data when
chain.doFilter()
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
HttpServletResponseWrapper
, implemented it, passed it to the Filter and it's working fine now.

Answer

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.

Comments