url路径中文参数乱码问题
作者:互联网
问题
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);
}
测试可以解决问题!
标签:中文,UTF,name,url,converters,乱码,return,false,public 来源: https://blog.51cto.com/happywzy/2870587