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);
}

测试可以解决问题!


文章作者: wuzhiyong
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 wuzhiyong !
评论
  目录