問題
http://localhost:8080/test?name=管理
這樣參數存在中文情況,spring boot
代碼
public RoleResponse selectById(@RequestParam(value = "name", required = false) String name){
return roleService.selectByName(name);
}
可能存在接收到的name
是%E7%AE%A1%E7%90%86
這樣的情況,這是瀏覽器自動爲URL
做了UrlEncode
;
即使你的application.yml
配置了UTF-8
編碼,也不一定能解決這樣的問題:
# application.properties
server:
tomcat:
uri-encoding: UTF-8
spring:
http:
encoding:
charset: UTF-8
enabled: true
force: true
網上查找的方法一:【添加配置類】
@Configuration
public class CustomMVCConfiguration extends WebMvcConfigurerAdapter {
@Bean
public HttpMessageConverter<String> responseBodyConverter() {
StringHttpMessageConverter converter = new StringHttpMessageConverter(
Charset.forName("UTF-8"));
return converter;
}
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
converters.add(responseBodyConverter());
}
@Override
public void configureContentNegotiation(
ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false);
}
}
測試並未解決問題!
方法二:【強制解碼】
public RoleResponse selectById(@RequestParam(value = "name", required = false) String name) throws UnsupportedEncodingException {
if (name != null){
name = URLDecoder.decode(name, "UTF-8");
}
return roleService.selectByName(name);
}
測試可以解決問題!