SpringBoot 过滤器请求参数统一处理

一、需求

每个操作,都需要记录到操作日志表,日志表里面需要存储请求方的IP地址。

 

二、思路

因为是非常详细的操作日志,尤其是编辑,需要记录编辑前后的数据,和业务强绑定,所以记录每个日志操作都需要放到方法内准备业务参数,单独调用接口进行保存,这个没有问题。但是请求方的ip地址,可以在过滤器内统一解析request获取,并且塞到请求参数内。

 

三、重写HttpServletRequestWrapper

SpringBoot 过滤器请求参数统一处理_第1张图片

这里也可以做公共入参校验,token校验之类的。

代码如下:

package com.zh.zohar.server.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zh.zohar.service.utils.HttpHelper;
import com.zh.zohar.service.utils.IPUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
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.Charset;

public class RequestReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private final String body;

    public RequestReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        //body = HttpHelper.getBodyString(request).getBytes(Charset.forName("UTF-8"));
        //body = HttpHelper.getBodyString(request);
        String ip = IPUtils.getRealIP(request);
        String bodyOld = HttpHelper.getBodyString(request);
        JSONObject js = JSON.parseObject(bodyOld);
        js.put("ip", ip);
        body = js.toJSONString();
    }

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

    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes(Charset.forName("UTF-8")));

        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) {

            }
        };
    }
}

四、写过滤器Filter

SpringBoot 过滤器请求参数统一处理_第2张图片

替换过滤器内request

代码如下:

package com.zh.zohar.server.config;

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

public class HttpServletRequestReplacedFilter implements Filter {

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest) {
            requestWrapper = new RequestReaderHttpServletRequestWrapper((HttpServletRequest) request);
        }
        //获取请求中的流如何,将取出来的字符串,再次转换成流,然后把它放入到新request对象中。
        // 在chain.doFiler方法中传递新的request对象
        if (requestWrapper == null) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }
    }

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

    }

}

 

五、注册过滤器到启动类

SpringBoot 过滤器请求参数统一处理_第3张图片

代码如下:

@Bean
public FilterRegistrationBean httpServletRequestReplacedRegistration() {
    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(new HttpServletRequestReplacedFilter());
    registration.addUrlPatterns("/*");
    registration.addInitParameter("paramName", "paramValue");
    registration.setName("httpServletRequestReplacedFilter");
    registration.setOrder(1);
    return registration;
}

六、附上从request内获取请求参数的工具类HttpHelper(注释有点小问题)

package com.zh.zohar.service.utils;

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;

/**
 * 获取请求ip
 */
public class HttpHelper {

    public static String getBodyString(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = request.getInputStream();
            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();
        } 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();
    }

}

 

 

 

你可能感兴趣的:(web,框架,spring,boot)