栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

仅当ContentType === JSON时才更改Java过滤器中的ContentType或CharacterEncoding

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

仅当ContentType === JSON时才更改Java过滤器中的ContentType或CharacterEncoding

多亏了此页面上的其他答案,我找到了一种实现方法。。。非常接近他们的建议,但是事实证明,使它起作用的唯一方法是重写“
getOutputStream”并查看此时的contentType。我已将此过滤器作为链中的第一个过滤器,它似乎工作正常。

import java.io.IOException;import javax.servlet.*;import javax.servlet.http.*;import javax.ws.rs.core.MediaType;public class EnsureJsonIsUtf8ResponseFilter implements Filter{    final String APPLICATION_JSON_WITH_UTF8_CHARSET = MediaType.APPLICATION_JSON + ";charset=" + java.nio.charset.StandardCharsets.UTF_8;    @Override    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException    {        HttpServletResponse r = (HttpServletResponse) response;        HttpServletResponse wrappedResponse = new HttpServletResponseWrapper(r)         { @Override public ServletOutputStream getOutputStream() throws java.io.IOException {     ServletResponse response = this.getResponse();     String ct = (response != null) ? response.getContentType() : null;     if (ct != null && ct.toLowerCase().startsWith(MediaType.APPLICATION_JSON))     {         response.setContentType(APPLICATION_JSON_WITH_UTF8_CHARSET);     }     return super.getOutputStream(); }        };        chain.doFilter(request, wrappedResponse);     }    @Override    public void init(FilterConfig filterConfig) throws ServletException    {        // This method intentionally left blank    }    @Override    public void destroy()    {        // This method intentionally left blank    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/570418.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号