在做springmvc开发的时候(javaweb)请求通过前端传递过来的时候,假如这个时候我想通过统一处理。实现方式如下
1、RequestParamLogFilter创建过滤器
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* 业务日志处理
*
*/
public class RequestParamLogFilter implements Filter {
private final Logger logger = LoggerFactory.getLogger(RequestParamLogFilter.class);
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
//这里通过自定义一个jsonContentRequest包装类进行包装请求,主要是需要获取请求里面的body
JsonContentRequestWrapper requestWrapper = new JsonContentRequestWrapper(httpServletRequest);
String uri = requestWrapper.getRequestURI();
String queryString = requestWrapper.getQueryString();
String body = new String(requestWrapper.getContentAsByteArray(), requestWrapper.getCharacterEncoding());
//这里暂时通过日志进行输出处理。后面可以通过数据库或者缓存或者消息服务把日志给发出去进行收集。
logger.info("into {} queryString:{},body:{}",uri,queryString,body);
chain.doFilter(requestWrapper, response);
}
}
2、JsonContentRequestWrapper 请求包装类实现
import org.springframework.http.HttpMethod;
import org.springframework.web.util.WebUtils;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
/**
* 缓存json参数
*
*/
public class JsonContentRequestWrapper extends HttpServletRequestWrapper {
//body参数都是通过json格式进行请求。后面判断请求的Content-Type类型的时候需要
private static final String JSON_CONTENT_TYPE = "application/json";
private final ByteArrayOutputStream cachedContent;
/**
* Create a new ContentCachingRequestWrapper for the given servlet request.
*
* @param request the original servlet request
*/
public JsonContentRequestWrapper(HttpServletRequest request) {
super(request);
//初始化cachedContent
this.cachedContent = new ByteArrayOutputStream();
//初始化完成后,从request里面把body里面的数据以流的方式装进去
writeJsonContentToCache();
}
@Override
public ServletInputStream getInputStream() throws IOException {
if (isJsonPost()) {
ByteArrayInputStream is = new ByteArrayInputStream(getContentAsByteArray());
return new ServletInputStream() {
private boolean finished;
@Override
public boolean isFinished() {
return finished;
}
@Override
public boolean isReady() {
return is.available() > 0;
}
@Override
public void setReadListener(ReadListener readListener) {
}
@Override
public int read() throws IOException {
int i;
finished = (i = is.read()) == 0;
return i;
}
};
}
return super.getInputStream();
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream(), getCharacterEncoding()));
}
//获取请求的编码,主要防止解码乱码问题
@Override
public String getCharacterEncoding() {
String enc = super.getCharacterEncoding();
return (enc != null ? enc : WebUtils.DEFAULT_CHARACTER_ENCODING);
}
//判断请求类型是不是application/json,
private boolean isJsonPost() {
String contentType = getContentType();
//请求类型还必须是post哟
//getMethod()是父类的方法。
return (contentType != null && contentType.contains(JSON_CONTENT_TYPE) &&
HttpMethod.POST.matches(getMethod()));
}
//将请求里面的数据流装到缓存中
private void writeJsonContentToCache() {
//判断请求类型是不是需要处理,因为这个是有body-json类型请求,记录才有用。其他类型记录没啥用
if (isJsonPost()) {
try (InputStream is = getInputStream()) {
int i;
while ((i=is.read()) != -1) {
cachedContent.write(i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public byte[] getContentAsByteArray() {
return this.cachedContent.toByteArray();
}
}
3、配置filter为bean,然后加载到spring容器(filter生效)
//测试项目是基于springboot,也就是说把这个filter-bean初始化导spring容器。就OK了
@Bean
public RequestParamLogFilter requestParamLogFilter(){
return new RequestParamLogFilter();
}
4、测试
body参数
控制台输出:
2021-04-15 10:24:50 INFO c.ysy.web.config.RequestParamLogFilter 27 : into /demo/getOpenIdPost queryString:code=sdfsfddsf,body:{
"userName":"郑大伟",
"userAdd":"收单方收单方是发",
"china":"中国"
}
===能看到打印出来的请求参数,请求地址,以及body参数。