仅在Java Filter中更改ContentType或CharacterEncoding如果ContentType === JSON [英] Change ContentType or CharacterEncoding in Java Filter ONLY IF ContentType === JSON

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

问题描述

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

所以如果这是一个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;
$ b public class EnsureJsonResponseIsUtf8Filter implements Filter
{
private class SimpleWrapper extends HttpServletResponseWrapper
{
public SimpleWrapper(HttpServletResponse响应)
{
超级(响应);
}

@Override
public String getCharacterEncoding()
{
returnUTF-8;


$ b @Override $ b $ 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()
{
}
}

我见过其他类似的问题,但没有一个他们似乎有这个问题。我已经尝试注册我的过滤器作为第一个和最后一个过滤器没有运气。

解决方案

感谢对此的其他答案页面,我找到了一个方法来做到这一点....非常接近他们的建议,但事实证明,我能得到它的唯一办法是重写getOutputStream,并在那个点看contentType。我已经把这个过滤器作为链中的第一个过滤器,它似乎工作正常。

  import java.io. IOException异常; 
import javax.servlet。*;
import javax.servlet.http。*;
import javax.ws.rs.core.MediaType;
$ b $ public class EnsureJsonIsUtf8ResponseFilter implements Filter
{
final String APPLICATION_JSON_WITH_UTF8_CHARSET = MediaType.APPLICATION_JSON +; charset =+ java.nio.charset.StandardCharsets.UTF_8;
$ b @Override $ b $ 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);

$ b @Override
public void init(FilterConfig filterConfig)throws ServletException
{
//这个方法故意留空
}
$ b $ @覆盖
public void destroy()
{
//此方法故意留空
}
}


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.

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

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

EDIT: I know I can do this on a case by case basis, but I'd like to do it globally, so it affects all content responses that have a content type of "application/json".

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.

解决方案

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

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

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