springboot增加过滤器后中文乱码

记录一下小问题

java 复制代码
public class RepeatableHttpServletWrapper extends HttpServletRequestWrapper {
    private  byte[] body;

    public RepeatableHttpServletWrapper(HttpServletRequest request) throws IOException  {
        super(request);
        request.setCharacterEncoding("UTF-8");
        BufferedReader reader = request.getReader();
        try (StringWriter writer = new StringWriter()) {
            int read;
            char[] buf = new char[1024];
            while ((read = reader.read(buf)) != -1) {
                writer.write(buf, 0, read);
            }
            this.body = writer.getBuffer().toString().getBytes(StandardCharsets.UTF_8);
        }
    }

    public String getBody(){
        return new String(body, StandardCharsets.UTF_8);
    }

    @Override
    public ServletInputStream getInputStream() {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }
            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }

            @Override
            public int read() {
                return byteArrayInputStream.read();
            }
        };
    }
    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(this.getInputStream(), StandardCharsets.UTF_8));
    }
}
java 复制代码
public class RepeatableWrapperFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (servletRequest.getCharacterEncoding() == null) {
            servletRequest.setCharacterEncoding("UTF-8");
        }
        ServletRequest requestWrapper = null;
        if(servletRequest instanceof HttpServletRequest) {
            requestWrapper = new RepeatableHttpServletWrapper((HttpServletRequest) servletRequest);
        }
        if(requestWrapper == null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            filterChain.doFilter(requestWrapper, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
java 复制代码
    @Bean
    public FilterRegistrationBean repeatableWrapperFilter() {
        FilterRegistrationBean<RepeatableWrapperFilter> registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new RepeatableWrapperFilter());
        registrationBean.addUrlPatterns("/*");
        registrationBean.setOrder(1);
        registrationBean.setAsyncSupported(true);
        return registrationBean;
    }
java 复制代码
public class DataAuthenticationInterceptor implements HandlerInterceptor {


    private DataAuthenticationService dataAuthenticationService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         RepeatableHttpServletWrapper repeatableRequest = new RepeatableHttpServletWrapper(request);
         String body = repeatableRequest.getBody();
    }
              

之前做的一个功能需要 通过拦截器前置处理post请求中body的信息,由于body在request中是以流存在的,读完就没有了,所以需要增加一个过滤器来进行前置处理,在处理时候本地是正常的发布linux后出现中文乱码情况

方法1:在启动jvm的参数中增加 -Dfile.encoding=UTF-8

java 复制代码
java -jar -Dfile.encoding=UTF-8 jar包

方法2:在xml文件的build标签中增加 jvm参数处理

xml 复制代码
<plugin>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-maven-plugin</artifactId>
	<version>${spring-boot.version}</version>
	<configuration>
		<fork>true</fork>
		<jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
	</configuration>
</plugin>

方法3:处理读写是统一按照 UTF-8 处理

方法4: 增加 CharacterEncodingFilter 过滤器 ,这个过滤器优先级要高于新增的过滤器

java 复制代码
@Bean
public FilterRegistrationBean characterEncodingFilter() {
    CharacterEncodingFilter filter = new CharacterEncodingFilter();
    filter.setEncoding("UTF-8");
    filter.setForceEncoding(true);
    FilterRegistrationBean<CharacterEncodingFilter> registrationBean = new FilterRegistrationBean();
    registrationBean.setFilter(filter);
    registrationBean.addUrlPatterns("/*");
    registrationBean.setOrder(0);
    return registrationBean;
}
相关推荐
李小白663 分钟前
JavaEE初阶复习(JVM篇)
java·jvm·java-ee
程序员一诺7 分钟前
【爬虫开发】爬虫开发从0到1全知识教程第14篇:scrapy爬虫框架,介绍【附代码文档】
后端·爬虫·python·数据
Easonmax12 分钟前
【JavaEE】网络原理详解
java·java-ee
java_学习爱好者23 分钟前
SpringBoot配置文件多环境开发
java
Asthenia041223 分钟前
Spring事件机制:微服务架构下的子服务内部解耦合/多场景代码分析
后端
别来无恙✲35 分钟前
SpringBoot启动方法分析
java·springboot·场景设计
Asthenia041237 分钟前
面试官问我:Spring AOP的代理模式与实现原理深度剖析
后端
Jay_See42 分钟前
Leetcode——239. 滑动窗口最大值
java·数据结构·算法·leetcode
小马爱打代码1 小时前
Spring Boot - 实现邮件发送
spring boot·后端
褚翾澜1 小时前
Ruby语言的代码重构
开发语言·后端·golang