基于Springboot拦截器记录操作日志(二)Request获取不到Body参数

紧接上一篇文章展开主题,上篇链接:https://blog.csdn.net/qq_42227281/article/details/106869400

本篇:Request 获取Post请求 body的参数

1、Springboot配置过滤器

需要注意的是,我用的是springboot,自定义的filter 需要扫描,或者加注解才能生效,我这里加了注解

@WebFilter(filterName = "requestFilter", urlPatterns = "/*")

启动类开启@ServletComponentScan,@WebFilter才能生效

@ServletComponentScan
@SpringBootApplication//springboot注解
public class ConformityApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConformityApplication.class, args);
    }

}

如果是基于xml配置的框架,就直接在xml中开启就可以了

package com.jsonmedia.common.utils;

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

/**
 * @Author: 王文龙
 * @Date: 2020/6/89:33
 * @Version: 1.0
 * @Describe: 描述:
 */
@WebFilter(filterName = "requestFilter", urlPatterns = "/*")
public class RequestFilter implements Filter{

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

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request1 = (HttpServletRequest) request;
        if(Objects.isNull(request1.getHeader("Content-Type")) || request1.getHeader("Content-Type").contains("multipart/form-data;")){
            chain.doFilter(request,response);
        }else {
            chain.doFilter(new InputStreamReadRepeatableRequestWrapper(request1), response);
        }
    }

    @Override
    public void destroy() {

    }
}

2、由于inputStream只能被读取一次,这时需要将流中数据存储起来,以便后续使用,继承HttpServletRequestWrapper

package com.it.conformity.common.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StreamUtils;

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

/**
 * @Author: 王文龙
 * @Date: 2020/6/2211:17
 * @Version: 1.0
 * @Describe: 描述:
 */
public class RequestWrapper extends HttpServletRequestWrapper {

    private Logger logger = LoggerFactory.getLogger(RequestWrapper.class);
    private String encoding = "UTF-8";
    private byte[] requestBodyIniBytes;

    public RequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        ServletInputStream stream = request.getInputStream();
        String requestBody = StreamUtils.copyToString(stream, Charset.forName(encoding));
        requestBodyIniBytes = requestBody.getBytes(encoding);

    }


    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream in;
        in = new ByteArrayInputStream(requestBodyIniBytes);
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

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

            @Override
            public void setReadListener(ReadListener listener) {

            }

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

3、获取流中数据

package com.it.conformity.common.util;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * 获取流中数据
 * @Author: 王文龙
 * @Date: 2020/6/2211:10
 * @Version: 1.0
 * @Describe: 描述:
 */
public class RequestHelper {

    /**
     * 获取流中的数据
     */
    private static Logger logger = LoggerFactory.getLogger(RequestHelper.class);
    public static Map getBodyString(ServletRequest request) {
        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) {
            logger.warn("getBodyString出现问题!");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return JSON.parseObject(sb.toString(),Map.class);
    }
}

4、在日志的工具类中直接调用RequestHelper 就可以拿到数据了

RequestHelper.getBodyString(request)获取处理后的body参数

package com.it.conformity.common.util;

import com.alibaba.fastjson.JSON;
import com.it.conformity.testdemo.dao.SysLogDao;
import com.it.conformity.testdemo.pojo.SysLog;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 保存日志的工具类
 *
 * @Author: 王文龙
 * @Date: 2020/6/2011:39
 * @Version: 1.0
 * @Describe: 描述:
 */
public class SysLogUtil {

    private static SysLogDao sysLogDao = SpringUtil.getApplicationContext().getBean(SysLogDao.class);

    /**
     * 保存日志
     */
    public static void saveLog(HttpServletRequest request, Exception ex, String title) throws Exception {
        SysLog log = new SysLog();
        log.setTitle(title);
        log.setType(ex == null ? "1" : "2");
        //登陆人获取这块还没法实现,这个框架是我私下整合其他插件用框架,后面把Shiro或者SpringSecruity
        log.setCreateBy("王文龙");
        log.setRemoteAddr(StringUtils.getRemoteAddr(request));
        log.setUserAgent(request.getHeader("user-agent"));
        log.setRequestUri(request.getRequestURI());        
        log.setParams(JSON.toJSONString(RequestHelper.getBodyString(request)));
        log.setMethod(request.getMethod());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        log.setCreateDate(format);
        // 保存日志
        boolean insert = sysLogDao.insert(log);
        Assert.isTrue(insert,"添加系统日志失败");

    }
}

 

你可能感兴趣的:(Request获取body参数,拦截器)