我正在尝试确保来自基于Jersey的
java应用程序的所有
JSON响应都在其ContentType标头中附加了UTF-8字符编码参数.
因此,如果它是JSON响应,我想要Content-Type的响应头
Content-Type: application/json;charset=UTF-8
编辑:我知道我可以根据具体情况这样做,但我想全局地这样做,因此它会影响内容类型为“application / json”的所有内容响应.
如果我只是尝试在我的过滤器中设置字符编码,无论内容类型如何,它都可以正常工作.但是我只想在ContentType为“application / json”时设置字符编码.我发现response.getContentType()方法总是返回null,除非我先调用chain.doFilter.但是如果我在此之后尝试更改字符编码,它似乎总是会被覆盖.
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.ws.rs.core.MediaType;
public class EnsureJsonResponseIsUtf8Filter implements Filter
{
private class SimpleWrapper extends HttpServletResponseWrapper
{
public SimpleWrapper(HttpServletResponse response)
{
super(response);
}
@Override
public String getCharacterEncoding()
{
return "UTF-8";
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
chain.doFilter(request, response);
if (response.getContentType() != null && response.getContentType().contains(MediaType.APPLICATION_JSON))
{
response.setCharacterEncoding("UTF-8");
chain.doFilter(request, new SimpleWrapper((HttpServletResponse) response));
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
}
@Override
public void destroy()
{
}
}
我见过其他similar questions,但他们似乎都没有这个问题.我已经尝试将我的过滤器注册为第一个,最后一个过滤器没有运气.