Using a javax.servlet.Filter
One way to do this in a portable way (across different app servers), is using Filters. In your web.xml add the following:
<filter>
<filter-name>headersFilter</filter-name>
<filter-class>MyHeadersFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>headersFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Then implement your MyHeadersFilter like:
public class MyHeadersFilter implements Filter {
@Override
public void doFilter(final ServletRequest request,
final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final String requestUri = httpRequest.getRequestURI();
final HttpServletResponse httpResponse = (HttpServletResponse) response;
if (requestUri.contains(".nocache.")) {
httpResponse.addHeader("Cache-Control", "no-cache");
...
} else if (...) {
...
}
chain.doFilter(request, response);
}
}
Optional: Configurable Filters
You can also make your filter configurable from your web.xml, by using <init-param>
s:
<filter>
<filter-name>headersFilter</filter-name>
<filter-class>MyHeadersFilter</filter-class>
<init-param>
<param-name>myParam</param-name>
<param-value>myValue</param-value>
</init-param>
</filter>
Add the following to MyHeadersFilter:
private FilterConfig filterConfig;
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
@Override
public void destroy() {
this.filterConfig = null;
}
That makes it possible to access your init-param(s) using:
filterConfig.getInitParameter("myParam")