spring - 如何使 Spring Boot 默认为 application/json;charset=utf-8 而不是 application/json;charset=iso-8859-1

标签 spring spring-boot configuration

我正在将 spring-boot 从 1.3.6 更新到 2.1.3,而之前响应的内容类型为 application/json;charset=UTF-8 ,现在我得到了一个 iso-8859-1 的字符集。

我想要utf 8。

我的 Controller 如下所示:

@Controller
public class MyController {
    @RequestMapping(value={"/myService/{serviceId}"}, method=RequestMethod.POST, consumes="application/json")
    public ResponseEntity<Void> handlePostServiceId(final InputStream requestInputStream,
            @PathVariable String serviceId,
            final HttpServletRequest servletRequest,) {
       <$businessLogic>
       return new ResponseEntity<>(new HttpHeaders(), HttpStatus.ACCEPTED);
}

如果我包含 produces= MediaType.APPLICATION_JSON_UTF8_VALUE,我可以让它返回 utf-8在我的@RequestMapping但我只想设置一次,而不是为每个 API 设置一次。

我也尝试添加
@Override
    public void configureContentNegotiation(
         ContentNegotiationConfigurer configurer) {
         configurer.defaultContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    }

按照这里的建议发送到我的 WebMvcConfigurer:https://stackoverflow.com/a/25275291/2855921但这破坏了我使用纯/文本内容类型的可用性 api。

我还确保我的请求是 UTF-8,因此它不仅仅是反射(reflect)我提供的格式。

关于如何将整个项目的字符集设置为 UTF-8 的任何想法?

最佳答案

将以下属性添加到 application.properties 文件:
对于 Spring Boot 1.x

# Charset of HTTP requests and responses. Added to the "Content-Type" 
# header if not set explicitly.
spring.http.encoding.charset=UTF-8
# Enable http encoding support.
spring.http.encoding.enabled=true
# Force the encoding to the configured charset on HTTP requests and responses.
spring.http.encoding.force=true
来源:https://docs.spring.io/spring-boot/docs/1.5.22.RELEASE/reference/html/common-application-properties.html
对于 Spring Boot 2.x
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.force-response=true
来源:https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#server.servlet.encoding.charset

关于spring - 如何使 Spring Boot 默认为 application/json;charset=utf-8 而不是 application/json;charset=iso-8859-1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55640629/

相关文章:

java - Spring配置-Arraylist的可选字段

linux - CVS linux 服务器项目太多,服务器命令结果为 "argument list too long"

java - 为什么 j_spring_security_check 404?

spring-boot - 谁调用了configureGlobal函数?如何调用configureGlobal函数?

javascript - 如何在 html thymeleaf 中使用变量作为参数

java - 将 JDK 参数正确传递到 Maven pom 文件中

java - Hazelcast:在集群上部署的正确方法

php - 如何为 PHP 正确配置 Nginx(Yii 框架和 Zurmo)

java - 为什么我的 Spring @Autowired 字段为空?

java - 如何使用 Spring MVC 和 Spring Security 为资源处理程序启用 HTTP 缓存