SpringBoot 攔截器獲取 @RequestBody 引數

邢闖洋發表於2022-08-30

前言

接手了一個 SpringBoot 專案,原本是用的 form-data 的格式來請求介面,但後來由於客戶端那邊說無法使用 form-data 格式請求介面,只好由我來修改原後端專案將請求格式一律改為 json 請求。

我看到該專案中寫了攔截器,所以我就在攔截器中使用 getInputStream 來讀取請求的 json 資料。

但是該方式只能讀取一次,所以當使用攔截器時,controller 已經不能獲取 body 中的引數。所以需要增加一個過濾器來解決,使流可以重複讀取。

實現方案分為兩個檔案,程式碼如下:

HttpContextUtils

package com.chuangyou.config;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * HttpContextUtils
 *
 * @author itdragons
 */
public class HttpContextUtils {

    /**
     * 獲取query引數
     *
     * @param request
     * @return
     */
    public static Map<String, String> getParameterMapAll(HttpServletRequest request) {
        Enumeration<String> parameters = request.getParameterNames();

        Map<String, String> params = new HashMap<>();
        while (parameters.hasMoreElements()) {
            String parameter = parameters.nextElement();
            String value = request.getParameter(parameter);
            params.put(parameter, value);
        }

        return params;
    }

    /**
     * 獲取請求Body
     *
     * @param request
     * @return
     */
    public static String getBodyString(ServletRequest request) {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = request.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

}

HttpServletRequest 過濾器:流可重複讀

package com.chuangyou.config;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
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;
import java.nio.charset.StandardCharsets;

/***
 * HttpServletRequest 過濾器
 * 解決: request.getInputStream()只能讀取一次的問題
 * 目標: 流可重複讀
 */
@Component
@WebFilter(filterName = "HttpServletRequestFilter", urlPatterns = "/")
@Order(10000)
public class HttpServletRequestFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if (servletRequest instanceof HttpServletRequest) {
            requestWrapper = new RequestWrapper((HttpServletRequest) servletRequest);
        }
        //獲取請求中的流如何,將取出來的字串,再次轉換成流,然後把它放入到新request物件中
        // 在chain.doFiler方法中傳遞新的request物件
        if (null == requestWrapper) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            filterChain.doFilter(requestWrapper, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }

    /***
     * HttpServletRequest 包裝器
     * 解決: request.getInputStream()只能讀取一次的問題
     * 目標: 流可重複讀
     */
    public class RequestWrapper extends HttpServletRequestWrapper {

        /**
         * 請求體
         */
        private String mBody;

        public RequestWrapper(HttpServletRequest request) {
            super(request);
            // 將body資料儲存起來
            mBody = getBody(request);
        }

        /**
         * 獲取請求體
         *
         * @param request 請求
         * @return 請求體
         */
        private String getBody(HttpServletRequest request) {
            return HttpContextUtils.getBodyString(request);
        }

        /**
         * 獲取請求體
         *
         * @return 請求體
         */
        public String getBody() {
            return mBody;
        }

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

        @Override
        public ServletInputStream getInputStream() throws IOException {
            // 建立位元組陣列輸入流
            final ByteArrayInputStream bais = new ByteArrayInputStream(mBody.getBytes(StandardCharsets.UTF_8));

            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() throws IOException {
                    return bais.read();
                }
            };
        }
    }
}

使用

上面兩個檔案放到合適的位置後,就可以在攔截器中使用 HttpContextUtils 獲取 body 體了。

String requestStr = HttpContextUtils.getBodyString(request);
JSONObject requestObj = JSON.parseObject(requestStr);

SpringBoot 攔截器獲取 @RequestBody 引數

參考文章

java 實現 HttpServletRequest raw 和 params 的方式 請求 和獲取 加requestMapping 設定UTF-8
Springboot攔截器獲取@RequestBody引數

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章