使用多个@RequestBody接收参数

时间:2025-04-01 08:13:19

原因:常规情况下,因为request的body只能读取一次,@RequestBody也只能解析一次,这就导致解析第二个的@RequestBody的时候stream已经关闭了,无法再次读取。话不多说,上货:

解决办法:两个类,直接copy即可。

import ;
import ;
import ;
import ;
import .*;

public class BodyReaderRequestWrapper extends HttpServletRequestWrapper {
    private final String body;

    /**
     *
     * @param request
     */
    public BodyReaderRequestWrapper(HttpServletRequest request) throws IOException{
        super(request);
        StringBuilder sb = new StringBuilder();
        InputStream ins = ();
        BufferedReader isr = null;
        try{
            if(ins != null){
                isr = new BufferedReader(new InputStreamReader(ins));
                char[] charBuffer = new char[128];
                int readCount = 0;
                while((readCount = (charBuffer)) != -1){
                    (charBuffer,0,readCount);
                }
            }else{
                ("");
            }
        }catch (IOException e){
            throw e;
        }finally {
            if(isr != null) {
                ();
            }
        }

        ();
        body = ();
    }

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

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayIns = new ByteArrayInputStream(());
        ServletInputStream servletIns = new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

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

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return ();
            }
        };
        return  servletIns;
    }
}
import ;

import .*;
import ;
import ;
import ;
import ;

@Component
@WebFilter(filterName = "crownFilter", urlPatterns = "/*")
public class BodyReaderRequestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)res;
        BodyReaderRequestWrapper requestWrapper  = new BodyReaderRequestWrapper(request);
        if(requestWrapper == null){
            (request,response);
        }else {
            (requestWrapper,response);
        }
    }

    @Override
    public void destroy() {

    }
}

使用:自行测试。