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

測試可以解決問題!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章