问题
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.propertiesserver:tomcat:uri-encoding: UTF-8spring:http:encoding:charset: UTF-8enabled: trueforce: true
网上查找的方法一:【添加配置类】
@Configurationpublic class CustomMVCConfiguration extends WebMvcConfigurerAdapter {@Beanpublic HttpMessageConverter<String> responseBodyConverter() {StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));return converter;}@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {super.configureMessageConverters(converters);converters.add(responseBodyConverter());}@Overridepublic 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);}
测试可以解决问题!