adam bien's blog

Convenient http filtering with Servlet 4.0 and Java EE 8 📎

HttpFilter was introduced with JSR 369 / Servlet 4.0 and Java EE 8.

The HttpServletRequest and HttpServletResponse parameters are directly passed to the HelloFilter#doFilter method:


import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter("/*")
public class HelloFilter extends HttpFilter {

    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, 
    FilterChain chain) throws IOException, ServletException {
        chain.doFilter(req, res);
        res.getWriter().print(" is great");
    }
}

The servlet does not know anything about the HelloFilter:


@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getWriter().print("Java EE 8");
    }

}

curl (...)/HelloServlet returns Java EE 8 is great.

See you at Java EE 8 on Java 9, at Munich Airport, Terminal 2