[英]How to get the content type from a ServletResponse?
I'm implementing a filter, which overrides the doFilter
method, to insert in the response header some "cache-control" values. 我正在实现一个覆盖doFilter
方法的过滤器,以便在响应标头中插入一些“缓存控制”值。 The thing is that I only want that values to be set in the responses with a JSON content type. 事实是,我只希望在响应中使用JSON内容类型设置值。 I tried to call response.getContentType
before set the new header values but it always evaluates to null. 在设置新的标头值之前,我尝试调用response.getContentType
,但它始终计算为null。
@Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
final FilterChain filterChain) throws IOException, ServletException {
try {
final HttpServletResponse response = (HttpServletResponse) servletResponse;
if(response != null) {
final HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(response);
if(wrapper.containsHeader(HttpHeaders.CONTENT_TYPE)
&& wrapper.getHeader(HttpHeaders.CONTENT_TYPE).equals("application/json")) {
response.setHeader("Expires", "Mon, 23 Aug 1982 12:00:00 GMT");
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
}
}
filterChain.doFilter(servletRequest, servletResponse);
}
catch(final Exception e) {
LOG.error(e.getLocalizedMessage());
}
}
The difficulty with servlet filters is that they are too coarse-grained for that kind of functionality. Servlet过滤器的困难在于,对于这种功能而言,它们的粒度太粗。 The doFilter
method is "all-or-nothing", that is there is nothing set in the response before it is called and the entire response is already committed after it returns so it's too late then to add any header. doFilter
方法是“ all-or-nothing”,即在调用之前没有在响应中设置任何内容,并且返回后整个响应都已提交,因此添加任何标头为时已晚。
What you can do instead is to wrap the response and intercept the setHeader
method in the wrapper, then pass that to doFilter
. 相反,您可以做的是包装响应并在包装器中拦截setHeader
方法,然后将其传递给doFilter
。 There is a helper class HttpServletResponseWrapper designed for that purpose. 为此目的设计了一个辅助类HttpServletResponseWrapper 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.