【问题标题】:Spring set default Content-type to "application/json;charset=utf-8" when Jackson is not used当不使用 Jackson 时,Spring 将默认 Content-type 设置为“application/json;charset=utf-8”
【发布时间】:2014-10-06 04:06:27
【问题描述】:

我想将我的 Spring 应用默认“Content-type”更改为“application/json;charset=utf-8”,而不仅仅是“application/json”

【问题讨论】:

  • 有具体原因吗? JSON 的默认编码是 UTF-8。
  • 我没有使用杰克逊。我的控制器正在返回 ResponseEntity,因此默认情况下是“应用程序/文本”。

标签: spring spring-mvc


【解决方案1】:

春天> 4.3.4

@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

【讨论】:

  • 这已被 > Spring 5.2 弃用
【解决方案2】:
@Configuration
@EnableWebMvc
public class MVCConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureContentNegotiation(
         ContentNegotiationConfigurer configurer) {
        final Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("charset", "utf-8");

        configurer.defaultContentType(new MediaType(
          MediaType.APPLICATION_JSON, parameterMap));
    }
}

【讨论】:

  • 您可以使用 new MediaType(MediaType.APPLICATION_JSON, Collections.singletonMap("charset", "utf-8")) 或 new MediaType("application", "json" , Charset.forName(" UTF-8"))。在新的春天有 MediaType.APPLICATION_JSON_UTF8
  • 同样在 Spring 4.3+ 你可以做new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8);
【解决方案3】:

我发现的默认内容类型字符集的最简单解决方案是使用请求过滤器:

@Component
public class CharsetRequestFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");

        filterChain.doFilter(request, response);
    }
}

【讨论】:

    【解决方案4】:

    修改产生

    例如:

    @RequestMapping(method = RequestMethod.GET, produces = { "application/json; charset=utf-8" })
    
    public @ResponseBody Object get1() {
    ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      • 2019-12-19
      • 2013-04-03
      相关资源
      最近更新 更多