Springboot經過攔截器攔截請求信息收集到日誌

一、需求

最近在工做中遇到的一個需求,將請求中的客戶端類型、操做系統類型、ip、port、請求方式、URI以及請求參數值收集到日誌中,網上找資料說用攔截器攔截全部請求而後收集信息,因而就開始了操做:前端

二、問題

試了以後發現當請求方式爲POST,前端發送數據json時只能用request.getReader()流獲取,自信滿滿從流中獲取以後發現請求以後報錯:java

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

因而網上找答案,發現是ServletRequest的getReader()和getInputStream()兩個方法只能被調用一次,並且不能兩個都調用。那麼若是Filter中調用了一次,在Controller裏面就不能再調用了。web

而後又開始找解決方法,說既然ServletInputStream不支持從新讀寫,就把流讀出來後用容器存儲起來,後面就能夠屢次利用了。spring

因而繼承 HttpServletRequestWrapper類(http請求包裝器,其基於裝飾者模式實現了HttpServletRequest界面)並實現想要從新定義的方法以達到包裝原生HttpServletRequest對象。還須要在過濾器裏將原生的HttpServletRequest對象替換成咱們的RequestWrapper對象。apache

測試發現POST請求參數值能夠在攔截器類中獲取到了,本覺得大功告成,又發現GET請求很差使了,開始報錯Stream closed,一頓操做發現須要在過濾器進行判斷,若是是POST請求走本身的繼承的HttpServletRequestWrapper類請求,不然走普通的請求。終於成功!忽然舒服了。json

二、獲取

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("/**");
    }
}
相關文章
相關標籤/搜索