Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring将默认内容类型设置为";应用程序/json;字符集=utf-8“;不使用Jackson时_Spring_Spring Mvc - Fatal编程技术网

Spring将默认内容类型设置为";应用程序/json;字符集=utf-8“;不使用Jackson时

Spring将默认内容类型设置为";应用程序/json;字符集=utf-8“;不使用Jackson时,spring,spring-mvc,Spring,Spring Mvc,我想将我的spring应用程序默认的“内容类型”更改为“application/json;charset=utf-8”,而不仅仅是“application/json”@Configuration @EnableWebMvc 公共类MVCConfig扩展了WebMVCConfigureAdapter{ @凌驾 公共无效配置内容协商( ContentNegotiationConfigurer(配置器){ 最终映射参数Map=newhashmap(); 参数映射put(“字符集”、“utf-8”);

我想将我的spring应用程序默认的“内容类型”更改为“application/json;charset=utf-8”,而不仅仅是“application/json”

@Configuration
@EnableWebMvc
公共类MVCConfig扩展了WebMVCConfigureAdapter{
@凌驾
公共无效配置内容协商(
ContentNegotiationConfigurer(配置器){
最终映射参数Map=newhashmap();
参数映射put(“字符集”、“utf-8”);
configurer.defaultContentType(新媒体类型(
MediaType.applicationu JSON,parameterMap));
}
}
修改产品

例如:

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

public @ResponseBody Object get1() {
...
}
弹簧>4.3.4

@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

通过使用请求筛选器,我找到了默认内容类型字符集的最简单解决方案:

@组件
公共类CharsetRequestFilter扩展了OncePerRequestFilter{
@凌驾
受保护的无效doFilterInternal(HttpServletRequest请求,
HttpServletResponse,FilterChain FilterChain)引发ServletException,IOException{
响应。setCharacterEncoding(“UTF-8”);
filterChain.doFilter(请求、响应);
}
}

有什么具体原因吗?JSON的默认编码是UTF-8。我没有使用Jackson。我的控制器正在返回ResponseEntity,因此默认为“application/text”。您可以使用新的MediaType(MediaType.application\u JSON,Collections.singletonMap(“charset”,“utf-8”))或新的MediaType(“application”,“JSON”,charset.forName(“utf-8”))。在新的Spring中有MediaType.APPLICATION_JSON_UTF8,在Spring 4.3+中,您也可以执行
新的MediaType(MediaType.APPLICATION_JSON,StandardCharsets.UTF_8)这是从>Spring 5.2中弃用的
@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)