Springboot通過攔截器攔截請求資訊收集到日誌

Leil_blogs發表於2021-08-12

1、需求

最近在工作中遇到的一個需求,將請求中的客戶端型別、作業系統型別、ip、port、請求方式、URI以及請求引數值收集到日誌中,網上找資料說用攔截器攔截所有請求然後收集資訊,於是就開始了操作:

2、問題

試了之後發現當請求方式為POST,前端傳送資料json時只能用request.getReader()流獲取,自信滿滿從流中獲取之後發現請求之後報錯:

getInputStream() has already been called for this request...

於是網上找答案,發現是ServletRequest的getReader()和getInputStream()兩個方法只能被呼叫一次,而且不能兩個都呼叫。那麼如果Filter中呼叫了一次,在Controller裡面就不能再呼叫了。

然後又開始找解決方法,說既然ServletInputStream不支援重新讀寫,就把流讀出來後用容器儲存起來,後面就可以多次利用了。

於是繼承 HttpServletRequestWrapper類(http請求包裝器,其基於裝飾者模式實現了HttpServletRequest介面)並實現想要重新定義的方法以達到包裝原生HttpServletRequest物件。還需要在過濾器裡將原生的HttpServletRequest物件替換成我們的RequestWrapper物件。

測試發現POST請求引數值可以在攔截器類中獲取到了,本以為大功告成,又發現GET請求不好使了,開始報錯Stream closed,一頓操作發現需要在過濾器進行判斷,如果是POST請求走自己的繼承的HttpServletRequestWrapper類請求,否則走普通的請求。終於成功!突然舒服了。

2、獲取

1)匯入依賴為了獲取客戶端型別、作業系統型別、ip、port

<dependency>
            <groupId>eu.bitwalker</groupId>
            <artifactId>UserAgentUtils</artifactId>
            <version>1.21</version>
</dependency>

2)封裝獲取body字串的工具類

package com.btrc.access.util;

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.Charset;

public class RequestUtil {
    public static String getBodyString(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        try (
                InputStream inputStream = request.getInputStream();
               BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")))
        ) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}

3)攔截器類

package com.btrc.access.filter;

import com.btrc.access.util.RequestUtil;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 請求攔截器:攔截請求目的是將請求的資訊收集到日誌
 */
public class RequestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("user-agent"));
        //客戶端型別
        String clientType = userAgent.getOperatingSystem().getDeviceType().getName();
        //客戶端作業系統型別
        String osType = userAgent.getOperatingSystem().getName();
        //客戶端ip
        String clientIp = request.getRemoteAddr();
        //客戶端port
        int clientPort = request.getRemotePort();
        //請求方式
        String requestMethod = request.getMethod();
        //客戶端請求URI
        String requestURI = request.getRequestURI();
        //客戶端請求引數值
        String requestParam;
        //如果請求是POST獲取body字串,否則GET的話用request.getQueryString()獲取引數值
        if(StringUtils.equalsIgnoreCase(HttpMethod.POST.name(), requestMethod)){
            requestParam = RequestUtil.getBodyString(request);
        }else{
            requestParam = request.getQueryString();
        }
        //客戶端整體請求資訊
        StringBuilder clientInfo = new StringBuilder();
        clientInfo.append("客戶端資訊:[型別:").append(clientType)
                .append(", 作業系統型別:").append(osType)
                .append(", ip:").append(clientIp)
                .append(", port:").append(clientPort)
                .append(", 請求方式:").append(requestMethod)
                .append(", URI:").append(requestURI)
                .append(", 請求引數值:").append(requestParam.replaceAll("\\s*", ""))
                .append("]");
        
        //***這裡的clientInfo就是所有資訊了,請根據自己的日誌框架進行收集***
        System.out.println(clientInfo);
        
		//返回ture才會繼續執行,否則一直攔截住
        return true;
    }
}

4)繼承 HttpServletRequestWrapper類

package com.btrc.access.filter;

import com.btrc.access.util.RequestUtil;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;

public class AccessRequestWrapper extends HttpServletRequestWrapper {
    private final byte[] body;

    public AccessRequestWrapper(HttpServletRequest request) {
        super(request);
        body = RequestUtil.getBodyString(request).getBytes(Charset.forName("UTF-8"));
    }

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

    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream bais = new ByteArrayInputStream(body);

        return new ServletInputStream() {

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

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

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

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }
}

5)過濾器類

package com.btrc.access.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpMethod;

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

public class AccessFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //如果是POST走自己的繼承的HttpServletRequestWrapper類請求,否則走正常的請求
        if(StringUtils.equalsIgnoreCase(HttpMethod.POST.name(), request.getMethod())){
            //一定要在判斷中new物件,否則還會出現Stream closed問題
            filterChain.doFilter(new AccessRequestWrapper(request),servletResponse);
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}

6)攔截器過濾器配置類

package com.btrc.access.config;

import com.btrc.access.filter.AccessFilter;
import com.btrc.access.filter.RequestInterceptor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.Filter;

/**
 * 攔截器過濾器配置類
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Bean
    public FilterRegistrationBean httpServletRequestReplacedFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new AccessFilter());
        // /* 是全部的請求攔截,和Interceptor的攔截地址/**區別開
        registration.addUrlPatterns("/*");
        registration.setName("accessRequestFilter");
        registration.setOrder(1);
        return registration;
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RequestInterceptor()).addPathPatterns("/**");
    }
}

相關文章