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 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;

public class HelloFilter extends HttpFilter {

    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:

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


Just one question, maybe a stupid question:
The main benefit seems to be, that the registration in web.xml is not necessary as it was with Servlet v3, right?

Posted by Sven on November 16, 2017 at 06:05 PM CET #

So... Finally... Type casting not required...

Posted by Venkat on November 16, 2017 at 07:19 PM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments