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;
}
相关推荐
blammmp5 分钟前
Java:数据结构-枚举
java·开发语言·数据结构
暗黑起源喵23 分钟前
设计模式-工厂设计模式
java·开发语言·设计模式
WaaTong28 分钟前
Java反射
java·开发语言·反射
齐 飞1 小时前
MongoDB笔记01-概念与安装
前端·数据库·笔记·后端·mongodb
狂放不羁霸1 小时前
idea | 搭建 SpringBoot 项目之配置 Maven
spring boot·maven·intellij-idea
九圣残炎1 小时前
【从零开始的LeetCode-算法】1456. 定长子串中元音的最大数目
java·算法·leetcode
wclass-zhengge1 小时前
Netty篇(入门编程)
java·linux·服务器
LunarCod1 小时前
WorkFlow源码剖析——Communicator之TCPServer(中)
后端·workflow·c/c++·网络框架·源码剖析·高性能高并发
计算机学长felix1 小时前
基于SpringBoot的“校园交友网站”的设计与实现(源码+数据库+文档+PPT)
数据库·spring boot·毕业设计·交友
Re.不晚2 小时前
Java入门15——抽象类
java·开发语言·学习·算法·intellij-idea