我看到有一个similar question,但找不到正确的答案..
任何新的答案将不胜感激。
最佳答案
尝试这个:
定义一个添加响应头的过滤器:
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
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 java.io.IOException;
/**
* A filter that modifies a response.
* <p>
* Init-parameters:
* <ul>
* <li>headers: A comma-separated list of init-parameter names. Each init-parameter represents a
* response header to set. Each header value may contain multiple comma-separated values.</li>
* </ul>
* Sample usage:
* <pre>
* {@code
* FilterHolder responseFilter = dynamicResources.addFilter(ResponseFilter.class, "*.js",
* EnumSet.allOf(DispatcherType.class));
* responseFilter.setInitParameter("headers", "Cache-Control");
* responseFilter.setInitParameter("Cache-Control", "max-age=60");
* }
* </pre>
*
* @author Gili Tzabari
*/
public class ResponseFilter implements Filter
{
private final Multimap<String, String> headers = HashMultimap.create();
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
String headerNames = filterConfig.getInitParameter("headers");
if (headerNames == null)
return;
for (String name : headerNames.split(","))
{
String values = filterConfig.getInitParameter(name);
if (values == null)
continue;
for (String value : values.split(","))
headers.put(name, value);
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
if (response instanceof HttpServletResponse)
{
HttpServletResponse httpResponse = (HttpServletResponse) response;
for (String key : headers.keySet())
for (String value : headers.get(key))
httpResponse.addHeader(key, value);
}
chain.doFilter(request, response);
}
@Override
public void destroy()
{
}
}
配置Jetty以将缓存头注入特定的URL模式:
FilterHolder responseFilter = dynamicResources.addFilter(ResponseFilter.class, "*.js",
EnumSet.allOf(DispatcherType.class));
responseFilter.setInitParameter("headers", "Cache-Control");
responseFilter.setInitParameter("Cache-Control", "max-age=60");