Filter Requests with JEE 6 / 7
A tiny but shiny improvement with Java EE 6 was the @WebFilter – Annotation which made the filtering and manipulating of requests very easy: No more com.sun.jersey.spi.container.ContainerResponseFilters entries in the web.xml.
All you have to do is to implements the Filter-Interface and annotate your class:
package com.fpm.playground.internal.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter("/*")
public class CacheFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain){
try {
// manipulate response
chain.doFilter(request, response);
} catch (IOException e) {
//TODO handle exception
} catch (ServletException e) {
//TODO handle exception
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
With this solutions it’s very easy to enable CORS in REST-Requests or seperatly cache some resources while others have to refresh every request.