How to use HttpServletRequest#getParts() in a servlet filter running on Tomcat?

In order to get HttpServletRequest#getParts() to work in a Filter in Tomcat, you need to set allowCasualMultipartParsing=”true” in the webapp’s <Context> element in Webapp/META-INF/context.xml or Tomcat/conf/server.xml. <Context … allowCasualMultipartParsing=”true”> Because as per the servlet 3.0 specification the HttpServletRequest#getParts() should only be available inside a HttpServlet with the @MultipartConfig annotation. See also the documentation of the … Read more

ContentCachingResponseWrapper Produces Empty Response

After couple of hours of struggling, I’ve finally found the solution. In short, ContentCachingResponseWrapper.copyBodyToResponse() should be called in the end of the filter method. ContentCachingResponseWrapper caches the response body by reading it from response output stream. So, the stream becomes empty. To write response back to the output stream ContentCachingResponseWrapper.copyBodyToResponse() should be used.

Servlet filter runs in infinite redirect loop when user is not logged in

This AuthenticationFilter also runs when login.html is being requested. However, the code is redirecting to login.html once again instead of continuing the filter chain. This explains the infinite redirect loop. You need to let the filter just continue the request if the currently requested page is already the login page itself. E.g. public void doFilter(ServletRequest … Read more

Is there any easy way to preprocess and redirect GET requests?

If you’re homegrowing HTTP request authentication on top of JSF, then a servlet filter is really the best approach. JSF is “just” a MVC framework and nothing in the JSF API is been specified to filter incoming HTTP requests to check user authentication. On normal GET requests, a JSF managed bean is usually only constructed … Read more

How can I get the HTTP status code out of a ServletResponse in a ServletFilter?

First, you need to save the status code in an accessible place. The best to wrap the response with your implementation and keep it there: public class StatusExposingServletResponse extends HttpServletResponseWrapper { private int httpStatus; public StatusExposingServletResponse(HttpServletResponse response) { super(response); } @Override public void sendError(int sc) throws IOException { httpStatus = sc; super.sendError(sc); } @Override public … Read more

How do delete a HTTP response header?

You can’t delete headers afterwards by the standard Servlet API. Your best bet is to just prevent the header from being set. You can do this by creating a Filter which replaces the ServletResponse with a custom HttpServletResponseWrapper implementation which skips the setHeader()‘s job whenever the header name is Content-Disposition. Basically: @Override public void doFilter(ServletRequest … Read more