filter拦截器获取http请求参数

PS:里面一些方法使用了hutool的工具类 可以替换成你自己习惯的 工具类不是记录的主要东西。

记录点 1.怎么创建拦截器 2.怎么统一管理拦截器是否启用和输用顺序 3.怎么获取传入的参数 4.怎么获取返回值

直接上代码===================================================

filter配置

@Configuration 	
public class FilterConfig { 	  //log拦截器启动
    @Bean
    public FilterRegistrationBean logFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new LogFilter());
        registration.addUrlPatterns("/*");
        registration.setName("logFilter");
        registration.setOrder(Integer.MAX_VALUE-1);
        return registration;
    } 	}
1
2
3
4
5
6
7
8
9
10
11
12

LogFilter

/**
 * log过滤
 *
 * @author Teler
 */
public class LogFilter implements Filter {


    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {

        //为了在post的时候能继续传递
        LogHttpServletRequestWrapper request = new LogHttpServletRequestWrapper((HttpServletRequest) servletRequest);
        MyResponseWrapper response = new MyResponseWrapper((HttpServletResponse) servletResponse);

        StaticLog.info("=====================LogFilter前置start=====================>");

        //封装log实体类
         Map<String, Object> parameterMap=new LinkedHashMap<>();
        if("GET".equals(request.getMethod())){
            parameterMap= JSONUtil.parseObj(ServletUtil.getParams(request));
        }else{
            parameterMap= JSONUtil.parseObj(request.getBody());
        }
        StaticLog.info("请求来源: =》{}", request.getRemoteAddr());
        StaticLog.info("请求URI:{}", request.getRequestURI());
        StaticLog.info("请求方式:{}", request.getMethod());
        StaticLog.info("请求参数:{}", parameterMap);
        StaticLog.info("=====================LogFilter前置  end=====================>");
        //消耗时间
        long start = System.currentTimeMillis();

        // 执行主体方法start==================================================================
        chain.doFilter(request, response);
        // 执行主体方法  end==================================================================

        //耗时
        long time = System.currentTimeMillis() - start;
        StaticLog.info("=====================LogFilter后置start=====================>");
        byte[] content=response.getContent();
        String resultParams=new String();
        if (content.length > 0) {
            resultParams= new String(content, "UTF-8");
        }
             StaticLog.info("返回值:{}", resultParams);
        StaticLog.info("耗时(毫秒):", time);
        //返回消息 否则前台收不到消息
        servletResponse.getOutputStream().write(resultParams.getBytes());
        StaticLog.info("=====================LogFilter后置  end=====================>");
    }

    @Override
    public void destroy() {
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

LogHttpServletRequestWrapper.java

public class LogHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private final String body;

    public LogHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {

        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        body = stringBuilder.toString();
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
        ServletInputStream servletInputStream = 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 byteArrayInputStream.read();
            }
        };
        return servletInputStream;

    }

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

    public String getBody() {
        return this.body;
    }

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

MyResponseWrapper.java

public class MyResponseWrapper extends HttpServletResponseWrapper {
    private ByteArrayOutputStream buffer;

    private ServletOutputStream out;

    public MyResponseWrapper(HttpServletResponse httpServletResponse) {
        super(httpServletResponse);
        buffer = new ByteArrayOutputStream();
        out = new WrapperOutputStream(buffer);
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return out;
    }

    @Override
    public void flushBuffer()
            throws IOException {
        if (out != null) {
            out.flush();
        }
    }

    public byte[] getContent() throws IOException {
        flushBuffer();
        return buffer.toByteArray();
    }

    class WrapperOutputStream extends ServletOutputStream {
        private ByteArrayOutputStream bos;

        public WrapperOutputStream(ByteArrayOutputStream bos) {
            this.bos = bos;
        }

        @Override
        public void write(int b)
                throws IOException {
            bos.write(b);
        }

        @Override
        public boolean isReady() {

            // TODO Auto-generated method stub
            return false;

        }

        @Override
        public void setWriteListener(WriteListener arg0) {

            // TODO Auto-generated method stub

        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
上次更新: 2024-11-06, 19:27:10
最近更新
01
java playwright爬虫
11-06
02
连接chrome调试
07-23
03
连接chrome调试
07-23
更多文章>