Change ContentType or CharacterEncoding in Java Filter ONLY IF ContentType === JSON

前端 未结 6 1092
鱼传尺愫
鱼传尺愫 2021-01-01 04:32

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

6条回答
  •  执笔经年
    2021-01-01 05:15

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

提交回复
热议问题