Close

Java Servlet - Servlet Filter Examples

Java Servlet JAVA EE 


Java Servlet filter is an object that performs filtering tasks on the static or dynamic resource.

We need to implement Filter interface:

public interface Filter {
public void init(FilterConfig filterConfig) throws ServletException;
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException;
public void destroy();
}

The filter is mapped to an url pattern. The doFilter method of the filter is called by the container each time a resource is accessed withing that url pattern. doFilter() implementation can call FilterChain#doFilter method for the requested resource, or it might block it by not calling the method. destroy() and init() methods are life cycle methods for initialization and cleaning up the resources respectively.


Implementing the Filter interface to log request and response headers.

package com.logicbig.example;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

@WebFilter(urlPatterns = {"/*"})
public class HeaderLogFilter implements Filter {

@Override
public void init (FilterConfig filterConfig) throws ServletException {
}

@Override
public void doFilter (ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse rep = (HttpServletResponse) response;

System.out.println("----- Request ---------");
Collections.list(req.getHeaderNames())
.forEach(n -> System.out.println(n + ": " + req.getHeader(n)));

chain.doFilter(request, response);

System.out.println("----- response ---------");

rep.getHeaderNames()
.forEach(n -> System.out.println(n + ": " + rep.getHeader(n)));

System.out.println("response status: " + rep.getStatus());
}

@Override
public void destroy () {
}
}
Original Post




See Also