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

前端 未结 6 1202
鱼传尺愫
鱼传尺愫 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:14

    This is not going to work in this way.

    When you call chain.doFilter(request, response); your headers are already flushed and you can't reset them later on.

    What you can do is actually a quick and dirty trick:

    public void doFilter(...) {
        HttpServletResponse resp = new HttpServletResponseWrapper(response) {
        public void setContentType(String ct) {
            if(ct!=null && ct.toLowerCase().startsWith("application/json")) {
                super.setContentType("application/json;charset=UTF-8");
            } else {
                super.setContentType(ct);
            }
       }
    }
    
    // Set content type manually to override any potential defaults,
    // See if you need it at all
    response.setContentType("application/json;charset=UTF-8");
    
    chain.doFilter(request, resp); // Inject our response!
    }
    

    EDIT: ct.toUpperCase().startsWith("application/json") changed to ct.toLowerCase().startsWith("application/json").

提交回复
热议问题