一、场景
第一次搭建项目开发环境,需要在项目中实现日志拦截器,用来获取用户请求参数日志,以便在后期维护中出现BUG时能够快速定位错误发生的场景。请求参数一般通过GET和POST方式进行传递,GET请求参数获取通过request.getParameterMap()获取。而POST请求参数则采用request.getInputStream()获取。
二、错误
在实现中发现如果通过流获取参数,控制器中@RequestBody注解参数则获取不到。查看资料后,了解到spring中request.getInputStream() 和request.getReader()只能被获取一次,而@RequestBody注解参数的底层实现也是通过流来获取请求参数的。因此才出现了拦截器中通过流获取参数后,控制器中获取参数报错。
三、解决方案
1、日志拦截器类
package org.cm.channelmanage.web.interceptor;
import org.cm.channelmanage.web.handler.BodyReaderHttpServletRequestWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Map;
/**
* 日志拦截器
* author:xiaofan
* date:2018-08-15 10:26
*/
@Component
public class LogInterceptor extends HandlerInterceptorAdapter {
private Logger logger = LoggerFactory.getLogger(LogInterceptor.class);
private String getParamString(Map map) {
StringBuffer sb = new StringBuffer();
for (Map.Entry e : map.entrySet()) {
sb.append(e.getKey()).append("=");
String[] value = e.getValue();
if (value != null && value.length == 1) {
sb.append(value[0]).append("\t");
} else {
sb.append(Arrays.toString(value)).append("\t");
}
}
return sb.toString();
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
Long startTime = System.currentTimeMillis();
request.setAttribute("startTime",startTime);
try {
if(handler instanceof HandlerMethod){
StringBuilder sb = new StringBuilder();
sb.append("----------------------开始时间:")
.append(new SimpleDateFormat("hh:mm:ss.SSS")
.format(startTime)+"").append("------------\n");
sb.append("Controller:").append(((HandlerMethod) handler).getBean().getClass().getName()).append("\n");
sb.append("Method:").append(((HandlerMethod) handler).getMethod().getName()).append("\n");
sb.append("RequestMethod:").append(request.getMethod()).append("\n");
//通过输入流获取POST请求中的参数
sb.append("Params:").append(new BodyReaderHttpServletRequestWrapper(request).getBodyString()).append("\n");
sb.append("Params:").append(getParamString(request.getParameterMap())).append("\n");
sb.append("URL:").append(request.getRequestURL()).append("\n");
sb.append("SessionID:").append(request.getSession().getId()).append("\n");
sb.append("ApplyID:").append(request.getSession().getAttribute("applyId")).append("\n");
sb.append("OpenID:").append(request.getSession().getAttribute("openid")).append("\n");
logger.info(sb.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView){
Long startTime = (Long)request.getAttribute("startTime");
Long endTime = System.currentTimeMillis();
Long costTime = endTime - startTime;
if(handler instanceof HandlerMethod){
StringBuilder sb = new StringBuilder();
sb.append("CostTime:").append(costTime).append("ms");
logger.info(sb.toString());
}
}
}
2、自定义一个HttpServletRequestWrapper子类,用来封装HttpServletRequest请求
package org.cm.channelmanage.web.handler;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;
/**
* Request请求参数获取处理类
* author:XiaoFan
* 2018/09/18
*/
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {
private final byte[] body;
public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
String sessionStream = getBodyString(request);
body = sessionStream.getBytes(Charset.forName("UTF-8"));
}
public String getBodyString(){
return new String(body,Charset.forName("UTF-8"));
}
/**
* 获取请求Body
*
* @param request
* @return
*/
private String getBodyString(final ServletRequest request) {
StringBuilder sb = new StringBuilder();
InputStream inputStream = null;
BufferedReader reader = null;
try {
inputStream = cloneInputStream(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();
}
/**
* Description: 复制输入流
*
* @param inputStream
* @return
*/
public InputStream cloneInputStream(ServletInputStream inputStream) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
try {
while ((len = inputStream.read(buffer)) > -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
byteArrayOutputStream.flush();
}
catch (IOException e) {
e.printStackTrace();
}
InputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
return byteArrayInputStream;
}
@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) {
}
};
}
}
3、自定义一个过滤器将自定义的请求封装类传下去
package org.cm.channelmanage.web.filter;
import org.cm.channelmanage.web.handler.BodyReaderHttpServletRequestWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@WebFilter(urlPatterns = "/*",filterName = "channelFilter")
public class ChannelFilter implements Filter {
private Logger logger = LoggerFactory.getLogger(ChannelFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
logger.info("================进入过滤器======================");
// 防止流读取一次后就没有了, 所以需要将流继续写出去
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(httpServletRequest);
filterChain.doFilter(requestWrapper, servletResponse);
}
@Override
public void destroy() {
}
}