RequestWrapper.java 1.85 KB
package vion.config;

import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import org.dromara.hutool.core.io.IoUtil;

import java.io.*;

/**
 * 构建可重复读的流
 *
 * @author HlQ
 * @date 2024/1/25
 */
public class RequestWrapper extends HttpServletRequestWrapper {
    //参数字节数组
    private byte[] requestBody;

    //Http请求对象
    private HttpServletRequest request;

    public RequestWrapper(HttpServletRequest request) {
        super(request);
        this.request = request;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        // 每次调用此方法时将数据流中的数据读取出来,然后再回填到InputStream之中
        // 解决通过@RequestBody和@RequestParam(POST方式)读取一次后控制器拿不到参数问题
        if (null == this.requestBody) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            IoUtil.copy(request.getInputStream(), bos);
            this.requestBody = bos.toByteArray();
        }

        final ByteArrayInputStream bis = new ByteArrayInputStream(requestBody);
        return new ServletInputStream() {

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {
            }

            @Override
            public int read() {
                return bis.read();
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
}