借鉴别人的代码,重新做了处理,完整版。
在项目中,有两个场景会用到从 RequestBody 中读取内容。
- 打印请求日志
- 提供 Api 接口,在 Api 方法执行之前,从 RequestBody 中读取参数进行验签,验签通过后再执行 Api 方法的具体逻辑
这时就需要对 RequestBoy 进行重复读取。要实现对 RequestBody 进行重复读取的思路如下:
- 继承 HttpServletRequestWrapper 包装类,读取 RequestBody 的内容,然后缓存到 byte[] 数组 中;
- 增加过滤器,将包装类加入过滤器链中;
自定义 HttpServletRequestWrapper 包装类
由于采用采用application/json
传输参数时,HttpServletRequest只能读取一次 body 中的内容。因为是读的字节流,读完就没了,因此需要需要做特殊处理。为实现述多次读取 Request 中的 Body 内容,需继承 HttpServletRequestWrapper 类,读取 Body 的内容,然后缓存到 byte[] 中;这样就可以实现多次读取 Body 的内容了
package vip.xiaonuo.core.config.requestbody;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.io.IOUtils;
import java.io.*;
public class RequestWrapper extends HttpServletRequestWrapper {
//参数字节数组
private byte[] requestBody;
//Http请求对象
private HttpServletRequest request;
public RequestWrapper(HttpServletRequest request) throws IOException {
super(request);
this.request = request;
}
@Override
public ServletInputStream getInputStream() throws IOException {
/**
* 每次调用此方法时将数据流中的数据读取出来,然后再回填到InputStream之中
* 解决通过@RequestBody和@RequestParam(POST方式)读取一次后控制器拿不到参数问题
*/
if (null == this.requestBody) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(request.getInputStream(), baos);
this.requestBody = baos.toByteArray();
}
final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody);
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() {
return bais.read();
}
};
}
public byte[] getRequestBody() {
return requestBody;
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
}
增加过滤器,转换Request为自定义Request
package vip.xiaonuo.core.config.requestbody;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import java.io.IOException;
/**
* 请求拦截器,只有JSON数据才会使用自定义的RequestWrapper
*/
public class RequestBodyReaderFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if(servletRequest instanceof HttpServletRequest){
HttpServletRequest request = (HttpServletRequest) servletRequest;
if(StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)){
RequestWrapper requestWrapper = new RequestWrapper(request);
if(requestWrapper==null){
filterChain.doFilter(request,servletResponse);
}else {
filterChain.doFilter(requestWrapper,servletResponse);
}
return;
}
filterChain.doFilter(request,servletResponse);
}
filterChain.doFilter(servletRequest,servletResponse);
}
}
注册Filter
@Configuration
public class GlobalConfigure implements WebMvcConfigurer
{
@Bean
public FilterRegistrationBean<RequestBodyReaderFilter> fequestBodyReaderFilter() {
FilterRegistrationBean<RequestBodyReaderFilter> registrationBean = new FilterRegistrationBean<>();
RequestBodyReaderFilter filter = new RequestBodyReaderFilter();
registrationBean.setFilter(filter);
ArrayList<String> urls = new ArrayList<>();
urls.add("/*");//配置过滤规则
registrationBean.setUrlPatterns(urls);
registrationBean.setOrder(3);
return registrationBean;
}
}
前端使用
JSONObject jsonRequest = getJsonRequest(request); if(jsonRequest!=null){ paramValue=jsonRequest.getStr(paramName); }
private static JSONObject getJsonRequest(HttpServletRequest request) {
JSONObject result = null;
// log.info(">>> RequestMethod:{}", request.getMethod()+"|"+request.getContentType());
if(!StringUtils.startsWithIgnoreCase(request.getMethod(),"POST") ||
!StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)){
return result;
}
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = request.getReader();) {
char[] buff = new char[1024];
int len;
while ((len = reader.read(buff)) != -1) {
sb.append(buff, 0, len);
}
log.info(">>> RequestBody:{}", sb.toString());
result = JSONUtil.parseObj(sb.toString());
} catch (IOException e) {
log.error(">>>getJsonRequest: {}", e.getMessage());
}
return result;
}