spring boot 与spring mvc不同,在web应用中,默认的编码格式为UTF-8,而spring mvc的默认编码格式为iso-8859-1,在spring mvc中,如果设置编码格式需要在spring配置文件中加入:
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
但是在springboot中默认是utf-8,如果没有特殊需求,该编码不需要修改。如果要强制其他编码格式,spring boot提供三种设置方式
1. 通过在application.properties中设置
spring.http.encoding.charset=iso-8859-1
- 自定义StringHttpMessageConverter的Bean
@Bean
public StringHttpMessgeConverter stringHttpMessgeConverter(){
return new StringHttpMessgeConverter(Charset.forName("Utf-8");
}
- 实现WebMvcConfigurer,并重写addInterceptors
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
}
有些文档可能推荐继承WebMvcConfigurerAdapter,然后复写其中方法即可,但是从spring5.0开始,包括spring boot 2.0不在建议继承WebMvcConfigurerAdapter,而是直接实现WebMvcConfigurer,该接口中方法使用了java8中方法默认实现