SpringBoot拦截器中读取POST请求体参数

CustomHttpServletRequestWrapper.java:包装请求,缓存请求体数据,重写读取数据方法

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper {

    /**
     * 缓存请求体数据
     */
    private byte[] requestBody;

    public CustomHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        // 读取请求体并缓存
        requestBody = request.getInputStream().readAllBytes();
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        // 返回缓存的请求体字节流
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(requestBody);
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                return byteArrayInputStream.available() == 0;
            }

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

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }

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

    public byte[] getRequestBody() {
        return this.requestBody;
    }
}

RequestBodyCachingFilter:包装POST请求

import cn.hutool.extra.servlet.ServletUtil;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
// 确保过滤器优先执行
@Order(1)  
public class RequestBodyCachingFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        if (ServletUtil.METHOD_POST.equalsIgnoreCase(httpServletRequest.getMethod())) {
            // 包装 HttpServletRequest
            CustomHttpServletRequestWrapper wrappedRequest = new CustomHttpServletRequestWrapper(httpServletRequest);
            // 继续过滤链,传递包装后的请求对象
            chain.doFilter(wrappedRequest, response);
        } else {
            chain.doFilter(request, response);
        }
    }
}

CustomInterceptor.java:拦截器中取POST请求体的数据

import cn.hutool.extra.servlet.ServletUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

public class CustomInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (ServletUtil.METHOD_POST.equalsIgnoreCase(request.getMethod()) && request instanceof CustomHttpServletRequestWrapper) {
            CustomHttpServletRequestWrapper wrappedRequest = (CustomHttpServletRequestWrapper) request;
            String requestBody = getRequestBody(wrappedRequest);
            System.out.println("请求体内容为 >>> " + requestBody);
        }
        return true;
    }

    private String getRequestBody(CustomHttpServletRequestWrapper request) throws UnsupportedEncodingException {
        byte[] buf = request.getRequestBody();
        if (buf.length > 0) {
            return new String(buf, 0, buf.length, request.getCharacterEncoding());
        }
        return null;
    }
}

WebConfig:配置拦截器生效

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CustomInterceptor());
    }
}
posted @ 2024-09-19 11:02  黄河大道东  阅读(6)  评论(0编辑  收藏  举报