仅当 ContentType === JSON 时更改 Java 过滤器中的 ContentType 或 CharacterEncoding [英] Change ContentType or CharacterEncoding in Java Filter ONLY IF ContentType === JSON

查看:11
本文介绍了仅当 ContentType === JSON 时更改 Java 过滤器中的 ContentType 或 CharacterEncoding的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图确保来自基于 Jersey 的 Java 应用程序的所有 JSON 响应都将 UTF-8 字符编码参数附加到它们的 ContentType 标头中.

I'm trying to ensure that all JSON responses from a Jersey based java application have a UTF-8 character encoding parameter appended to their ContentType header.

因此,如果它是 JSON 响应,我希望 Content-Type 的响应标头为

So if it's a JSON response, I would like the response header for the Content-Type to be

内容类型:application/json;charset=UTF-8

Content-Type: application/json;charset=UTF-8

我知道我可以根据具体情况执行此操作,但我想在全局范围内执行此操作,因此它会影响所有内容类型为application/json"的内容响应.

如果我只是尝试在过滤器中设置字符编码而不管内容类型如何,它都可以正常工作.但如果 ContentType 是application/json",我只想设置字符编码.我发现 response.getContentType() 方法总是返回 null 除非我先调用 chain.doFilter .但是如果我在此之后尝试更改字符编码,它似乎总是被覆盖.

If I just try and set the character encoding in my filter regardless of the content type, it works fine. But I only want to set the character encoding if the ContentType is "application/json". I find that the response.getContentType() method always returns null unless I call chain.doFilter first. But if I try and change the Character Encoding after this, it seems to always get overwritten.

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()
    {
    }
}

我见过其他类似的问题,但都没有好像有这个问题.我尝试将我的过滤器注册为第一个和最后一个过滤器,但没有成功.

I've seen other similar questions, but none them seem to have this issue. I've tried registering my filter as the first, and last filter with no luck.

推荐答案

感谢本页上的其他答案,我找到了一种方法......非常接近他们的建议,但结果是我让它工作的唯一方法是覆盖getOutputStream"并在那时查看 contentType .我已将此过滤器作为链中的第一个过滤器,它似乎工作正常.

Thanks to the other answers on this page, I found a way to do it.... Very close to what they were suggesting, but it turned out the only way I could get it to work was to override "getOutputStream" and look at the contentType at that point. I've put this filter as the first filter in the chain, and it seems to work fine.

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
    }
}

这篇关于仅当 ContentType === JSON 时更改 Java 过滤器中的 ContentType 或 CharacterEncoding的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆