Java - Filters

java

// Filter:
@WebFilter(urlPattern = “*.do”)
public class LoginRequiredFilter implements Filter {
  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    if (request.getSession().getAttribute(“name”) != null) {
      chain.doFilter(servletRequest, servletResponse);
    } else {
      request.getRequestDispatcher(“/login.do”).forward(servletRequest, servletResponse);
    }
  }
}

<filter>
    <filter-name>logSpecial</filter-name>
    <filter-class>mysite.server.LogFilterImpl</filter-class>
    <init-param>
        <param-name>logType</param-name>
        <param-value>special</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>logSpecial</filter-name>
    <url-pattern>*.special</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>logSpecial</filter-name>
    <servlet-name>comingsoon</servlet-name>
</filter-mapping>

What can we use a filter for?

We can use a filter for a variety of things. For example:

  1. Ensure that the user is authenticated
  2. Compressing the content of the response

How can we implement a filter?

Define a class that implements the Filter interface, and use the @WebFilter annotation:

@WebFilter(urlPattern = “*.do”)
public class LoginRequiredFilter implements Filter {
  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    if (request.getSession().getAttribute(“name”) != null) {
      chain.doFilter(servletRequest, servletResponse);
    } else {
      request.getRequestDispatcher(“/login.do”).forward(servletRequest, servletResponse);
    }
  }
}

Instead of using the @WebFilter annotation, we can also register the filter in the web.xml file.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License