- A filter as the name suggests is a Java class executed by the servlet container for each incoming http request and for each http response. This way, is possible to manage HTTP incoming requests before them reach the resource, such as a JSP page, a servlet or a simple static page; in the same way is possible to manage HTTP outbound response after resource execution.
- The filter runs in the web container so its definition will also be contained in the web.xml file
- filer include three main methods:
- init: executed to initialize filter using init-param element in filter definition
- doFilter: executed for all HTTP incoming request that satisfy “url-pattern”
- release resources used by the filter
web.xml
<filter>
<filter-name>CORSFilter</filter-name>
<filter-class>com.listfeeds.components.CORSFilter</filter-class>
<init-param>
<param-name>fake-param</param-name>
<param-value>fake-param-value</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
TestFilter.java
package com.listfeeds.filters;
import java.io.IOException;
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.http.HttpServletResponse;
import org.springframework.stereotype.Component;
public class TestFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
Filters can perform many different types of functions.
- Authentication-Blocking requests based on user identity.
- Logging and auditing-Tracking users of a web application.
- Image conversion-Scaling maps
- Data compression-Making downloads smaller
- Localization-Targeting the request and response to a particular locale
Request Filters can:
- perform security checks
- reformat request headers or bodies
- audit or log requests
Response Filters can:
- Compress the response stream
- Append or alter the response stream
- Create a different response altogether
- Spring Interceptors are similar to Servlet Filters but they acts in Spring Context so are many powerful to manage HTTP Request and Response but they can implement more sophisticated behavior because can access to all Spring context.
- Developers can invoke interceptor methods in conjunction with method invocations or lifecycle events on an associated target class. Common uses of interceptors are logging, auditing, or profiling.
- Spring interceptor execute in Spring context so they have be defined in rest-servlet.xml file:
- The interceptor include three main methods:
- preHandle: executed before the execution of the target resource
- afterCompletion: executed after the execution of the target resource (after rendering the view)
- posttHandle: Intercept the execution of a handler
rest-servlet.xml
<mvc:interceptors>
<bean class="com.listfeeds.interceptors.LogContextInterceptor" />
<bean class="com.listfeeds.interceptors.TimedInterceptor" />
</mvc:interceptors>
LogContextInterceptor.java
public class LogContextInterceptor extends HandlerInterceptorAdapter
{
private static final Logger log = LoggerFactory.getLogger(LogContextInterceptor.class);
@Override
public void afterCompletion(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception
{
HandlerMethod methodHandler = (HandlerMethod) handler;
log.debug("END EXECUTION method {} request: {}", methodHandler.getMethod().getName(), request.getRequestURI());
}
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception
{
} catch (IllegalArgumentException e)
{
log.warn("Prehandle", e);
return true;
} finally
{
HandlerMethod methodHandler = (HandlerMethod) handler;
log.debug("START EXECUTION method {} request: {}", methodHandler.getMethod().getName(), request.getRequestURI());
}
return true;
}
For authentication of web pages you would use a servlet filter which acts at weblayer. For security stuff in your business layer or logging/bugtracing (a.k.a. independent of the web layer) you would use an Interceptor.