如何解决springboot参数传中⽂乱码
前⾔
本⽂案例来⾃业务部门的⼀个业务场景。他们的业务场景是他们部门研发了⼀个微服务上下⽂透传组件,其透传原理也挺简单的,就是通过springboot把请求参数塞进threadlocal,然后下游通过threadlocal取到值,服务之间进⾏feign调⽤时,再把threadlocal的参数塞到header头⾥⾯。这个组件⼀直⽤得好好的,突然有⼀天因为传的参数值是中⽂,导致乱码。他们通过尝试下⾯的各种⽅案,都⽆法解决。最后就让我们部门排查处理。
业务部门的实现思路
他们⼀开始的思路⽅向是参数编码不⼀致导致中⽂乱码。于是他们就朝这个⽅向努⼒着,于是就有了如下⽅案
⽅案⼀:
String value = new String("我是中⽂乱码".getBytes("ISO-8859-1"),"UTF-8");
这个是常⽤解决字符串中⽂乱码的⽅法之⼀
⽅案⼆:编写字符编码过滤器
@WebFilter(urlPatterns = "/*",filterName = "CharacterEncodingFilter")
public class CharacterEncodingFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
filterChain.doFilter(request , response);
}
@Override
public void destroy() {
}
}
然后启动类上加上@ServletComponentScan。@WebFilter是servlet3.0才有的注解。当然这个过滤器你还可以这么写
public class CharacterEncodingFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
filterChain.doFilter(request , response);
}
@Override
public void destroy() {
}
}
写个bean配置类,如下
@Bean
public FilterRegistrationBean registerAuthFilter() {springboot中文
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new CharacterEncodingFilter();
registration.addUrlPatterns("/*");
registration.setName("CharacterEncodingFilter");
registration.setOrder(1);
return registration;
}
⽅案三:在l指定编码格式为utf-8
spring:
http:
encoding:
charset: utf-8
enabled: true
force: true
server:
tomcat:
uri-encoding: UTF-8
⽅案四:写个StringHttpMessageConverter
百度来的基本上都是长这样。不过在spring5版本WebMvcConfigurerAdapter这个类已经过时。其替代⽅式是实现WebMvcConfigurer接⼝或者继承WebMvcConfigurationSupport。不过如果使⽤WebMvcConfigurationSupport,则会使springboot的mvc⾃动装配失效。失效的原因是
拓展⼀点⼩知识,加上@EnableWebMvc同样也会springboot的mvc⾃动装配失效。其原因是
org.springframework.fig.annotation.DelegatingWebMvcConfiguration这个配置类继承WebMvcConfigurationSupport
介绍那么多种⽅案,并没有解决按例的问题。那问题点出在哪⾥?前边案例我们提到过,在feign调⽤时,会把threadlocal的参数塞到header ⾥⾯。真正乱码的问题点就在这⾥,header是不⽀持中⽂传输的,如果你硬要传输,基本上接收⽅接到就是这种看似乱码的符号
破题关键
在把threadlocal的值塞到header⾥⾯时,先做下URLEncoder编码,形如
在接收header参数时,做下URLDecoder.解码,形如下
URLDecoder.decode(header中待解码的参数值, "UTF-8")
总结
⽅向错了,虽然再怎么努⼒看似也啥没卵⽤,不过⾄少可能会收获其他意想不到的东西
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论