HttpSevletRequest Body信息屢次讀取填坑錄-java

一、背景

業務攔截器須要攔截request的全部傳入信息。一般狀況下,HttpServletRequst 中的 body 內容只會讀取一次,可是可能某些情境下可能會讀取屢次,因爲 body 內容是以流的形式存在,因此第一次讀取完成後,第二次就沒法讀取了,一個典型的場景就是 Filter 在校驗完成 body 的內容後,業務方法就沒法繼續讀取流了,致使解析報錯。java

二、解決方案

咱們是否能夠用裝飾器來修飾一下 request,使其能夠包裝讀取的內容,供屢次讀取。web

這個裝飾器要符合httpsevletrequest接口規範,在原有的框架中spring boot提供了一個簡單的封裝器ContentCachingRequestWrapper,從源碼上看這個封裝器並不實用,沒有封裝http的底層流ServletInputStream信息,致使使用@RequestParam,@RequestBody等使用底層流構建的邏輯依然無用,只能硬生生的使用spring

public byte[] getContentAsByteArray() {
   return this.cachedContent.toByteArray();
}
複製代碼

來本身在業務中處理body信息。 這裏,我參照ContentCachingRequestWrapper封裝了一個更具可靠性,更低侵入性的裝飾器:apache

package com.interceptor;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.lang.Nullable;
import org.springframework.web.util.WebUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sean
 */
public class RepeatReadHttpRequest extends HttpServletRequestWrapper {
    private static final Logger LOGGER = LoggerFactory.getLogger(RepeatReadHttpRequest.class);
    private final ByteArrayOutputStream cachedContent;
    private Map<String, String[]> cachedForm;

    @Nullable
    private ServletInputStream inputStream;

    public RepeatReadHttpRequest(HttpServletRequest request) {
        super(request);
        this.cachedContent = new ByteArrayOutputStream();
        this.cachedForm = new HashMap<>();
        cacheData();
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        this.inputStream = new RepeatReadInputStream(cachedContent.toByteArray());
        return this.inputStream;
    }

    @Override
    public String getCharacterEncoding() {
        String enc = super.getCharacterEncoding();
        return (enc != null ? enc : WebUtils.DEFAULT_CHARACTER_ENCODING);
    }

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

    @Override
    public String getParameter(String name) {
        String value = null;
        if (isFormPost()) {
            String[] values = cachedForm.get(name);
            if (null != values && values.length > 0) {
                value = values[0];
            }
        }

        if (StringUtils.isEmpty(value)) {
            value = super.getParameter(name);
        }

        return value;
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        if (isFormPost() && !CollectionUtils.sizeIsEmpty(cachedForm)) {
            return cachedForm;
        }

        return super.getParameterMap();
    }

    @Override
    public Enumeration<String> getParameterNames() {
        if (isFormPost() && !CollectionUtils.sizeIsEmpty(cachedForm)) {
            return Collections.enumeration(cachedForm.keySet());
        }

        return super.getParameterNames();
    }

    @Override
    public String[] getParameterValues(String name) {
        if (isFormPost() && !CollectionUtils.sizeIsEmpty(cachedForm)) {
            return cachedForm.get(name);
        }

        return super.getParameterValues(name);
    }

    private void cacheData() {
        try {
            if (isFormPost()) {
                this.cachedForm = super.getParameterMap();
            } else {
                ServletInputStream inputStream = super.getInputStream();
                IOUtils.copy(inputStream, this.cachedContent);
            }
        } catch (IOException e) {
            LOGGER.warn("[RepeatReadHttpRequest:cacheData], error: {}", e.getMessage());
        }

    }

    private boolean isFormPost() {
        String contentType = getContentType();
        return (contentType != null &&
                (contentType.contains(MediaType.APPLICATION_FORM_URLENCODED_VALUE) ||
                        contentType.contains(MediaType.MULTIPART_FORM_DATA_VALUE)) &&
                HttpMethod.POST.matches(getMethod()));
    }

    private static class RepeatReadInputStream extends ServletInputStream {
        private final ByteArrayInputStream inputStream;

        public RepeatReadInputStream(byte[] bytes) {
            this.inputStream = new ByteArrayInputStream(bytes);
        }

        @Override
        public int read() throws IOException {
            return this.inputStream.read();
        }

        @Override
        public int readLine(byte[] b, int off, int len) throws IOException {
            return this.inputStream.read(b, off, len);
        }

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

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

        @Override
        public void setReadListener(ReadListener listener) {

        }
    }
}
複製代碼

使用這個裝飾器時須要配合Filter對原有的request進行偷樑換柱,註冊Filter並在調用鏈中將原有的request換成bash

RepeatReadHttpRequest
package com.interceptor;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author sean
 * 攔截器httprequest替換 可重複獲取inputstream
 */
@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean requestReplaceFilterRegistration() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new RequestReplaceFilter());
        registrationBean.addUrlPatterns("/*");
        registrationBean.setName("RequestReplaceFilter");
        registrationBean.setOrder(1);
        return registrationBean;
    }

    public static class RequestReplaceFilter implements Filter {
        @Override
        public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {

        }

        @Override
        public void destroy() {

        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            filterChain.doFilter(new RepeatReadHttpRequest((HttpServletRequest) servletRequest), servletResponse);
        }
    }
}
複製代碼

後續的request就能夠使用封裝器屢次讀取body信息。app

相關文章
相關標籤/搜索