1. 概述
在使用springboot开发接口时,会将参数转化为Bean,用来进行参数的自动校验。同时也想获取request中原始body报文进行验签(防止报文传输过程中被篡改)。
因为通过将bean再转化为字符串后,body里面的报文格式、字段顺序会发生改变,就会导致验签失败。因此只能通过request来获取body里面的内容。
既想接口自动实现参数校验,同时又想获取request中的原始报文,因此我们可以通过在controller中的restful方法中,写入两个参数,获取多次request中的body内容。
那么如何实现多次读取body内容了(因为request里的body是以字节流的方式读取的,默认情况下读取一次,字节流就没有了),下面就来大致分析一下。
2 接口接收参数的其他方式
2.1 接收参数方法一
方法一、
public R list(@RequestBody String rawMsg)
采用上述方式可以直接获得请求报文中的原始body信息,而且当body是一个json字符串时,rawMsg参数接口到的body值,不会改变json中key的顺序,即与发送方的body内容是保持一致的。这种方式可以用来对报文验签,因为被加密的字符串与发送方是保持一致的。
这种方式可以接受request里面body内容的原始格式,保持与发送方一致。
如下就可以对原始报文进行验签操作了
// 用公钥,对原始报文进行验签,在这里如果rawMsg里面是json时,当key的顺序改变后,会验签失败,
//如此我们可以通过request来获取body里面的原始报文
boolean verifyResult = SignVerifyUtils.verifySignature(rawMsg, Constant.NPIS_PUBLIC_KEY);
2.2 接收参数方法二
方法二、
public R list(@RequestBody @Validated ReqBean<ABCReqBean> abcReqBean)
这种接受参数的方法,可以将request里的json报文,直接转换成对应的bean对象。并且可以用来校验参数,例如某个字段是必传的、某个字段的值最大是多少等等。例如
@NotNull(message = "日期字段不允许为空")
@Size(min = 8, max = 8, message = "日期字符串的长度必须为 8")
private String beginDate;
有没有一种方法,既能同时利用参数校验功能,又能获取原始body里的内容来进行验签呢,这时候就可以采用下面的第3中方法。
2.3 接收参数方法三
@RequestMapping(method = {RequestMethod.POST}, value = "/dataQry")
public R list(@RequestBody @Validated ReqBean<ABCReqBean> abcReqBean,HttpServletRequest request){
}
在这里就可以通过将报文转换成abcReqBean对象,并实现接口参数的自动校验功能;同时可以利用request获取原始报文来进行验签。
注意:由于在接收参数时,HttpServletRequest只能读取一次body内容(因为是读的字节流,读完就没了),因此我们需要需要做特殊处理,
下面来看一种基于SpringBoot来解决HttpServletRequest只能读取一次的问题。
2.3.1 继承HttpServletRequestWrapper包装类,每次读取body后,再将参数写会request
为解决上述多次读取request中的body内容的问题,我们只需要将以下两个类,放到项目中即可,并通过@Component来注测为spring bean即可
继承HttpServletRequestWrapper ,实现每次读取request中的body后,在将内容写回request。
package com.abcd.config;
import org.apache.commons.io.IOUtils;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
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 {
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()));
}
}
2.3.2 将包装类加入过滤器链
回写参数的包装类写好之后接下来就是加入过滤器链之中,如下:
package com.abcd.config;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Component
@WebFilter(filterName = "channelFilter", urlPatterns = {"/*"})
public class ChannelFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
try {
ServletRequest requestWrapper = null;
if (request instanceof HttpServletRequest) {
requestWrapper = new RequestWrapper((HttpServletRequest) request);
}
if (requestWrapper == null) {
chain.doFilter(request, response);
} else {
chain.doFilter(requestWrapper, response);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
}
@Override
public void destroy() {
}
}
解决springboot v2.2以上重复读取request body内容问题
一、需求
项目有两个场景会用到从Request的Body中读取内容。
1、打印请求日志
2、提供Api接口,在api方法执行前,从Request Body中读取参数进行验签,验签通过后在执行api方法
二、解决方案
2.1 自定义RequestWrapper
public class MyRequestWrapper extends HttpServletRequestWrapper {
private final String body;
public MyRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
this.body = RequestReadUtils.read(request);
}
public String getBody() {
return body;
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes());
return new ServletInputStream() {
...略
};
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
}
RequestReadUtils(网上抄的)
private static final int BUFFER_SIZE = 1024 * 8;
public static String read(HttpServletRequest request) throws IOException {
BufferedReader bufferedReader = request.getReader();
for (Enumeration<String> iterator = request.getHeaderNames(); iterator.hasMoreElements();) {
String type = iterator.nextElement();
System.out.println(type+" = "+request.getHeader(type));
}
System.out.println();
StringWriter writer = new StringWriter();
write(bufferedReader,writer);
return writer.getBuffer().toString();
}
public static long write(Reader reader,Writer writer) throws IOException {
return write(reader, writer, BUFFER_SIZE);
}
public static long write(Reader reader, Writer writer, int bufferSize) throws IOException
{
int read;
long total = 0;
char[] buf = new char[bufferSize];
while( ( read = reader.read(buf) ) != -1 ) {
writer.write(buf, 0, read);
total += read;
}
return total;
}
2.2 定义Filter
@WebFilter
public class TestFilter implements Filter{
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain){
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
MyRequestWrapper wrapper = WebUtils.getNativeRequest(request, MyRequestWrapper.class);
chain.doFilter(wrapper == null ? new MyRequestWrapper(request) :wrapper,servletRequest);
}
}
三、遇到问题
使用的SpringBoot v2.1.x版本
1、Form提交无问题
2、获取RequestBody无问题
使用SpringBoot v2.2.0以上版本(包括v2.3.x)
1、Form提交无法获取参数
2、获取RequestBody无问题
四、问题排查
经过排查,v2.2.x对比v2.1.x的不同在于一下代码差异:
BufferedReader bufferedReader = request.getReader();
-----------------
char[] buf = new char[bufferSize];
while( ( read = reader.read(buf) ) != -1 ) {
writer.write(buf, 0, read);
total += read;
}
当表单提交时
1、v2.1.x无法read到内容,读取结果为-1
2、v2.2.x、v2.3.x能够读取到内容
当表单提交时(x-www-form-urlencoded),inputStream读取一次后后续不会触发wrapper的getInputStream操作,所以Controller无法获取到参数。
解决方案
MyRequestWrapper改造
public class MyRequestWrapper extends HttpServletRequestWrapper {
private final String body;
public MyRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
this.body = getBodyString(request);
}
public String getBody() {
return body;
}
public String getBodyString(final HttpServletRequest request) throws IOException {
String contentType = request.getContentType();
String bodyString = "";
StringBuilder sb = new StringBuilder();
if (StringUtils.isNotBlank(contentType) && (contentType.contains("multipart/form-data") || contentType.contains("x-www-form-urlencoded"))) {
Map<String, String[]> parameterMap = request.getParameterMap();
for (Map.Entry<String, String[]> next : parameterMap.entrySet()) {
String[] values = next.getValue();
String value = null;
if (values != null) {
if (values.length == 1) {
value = values[0];
} else {
value = Arrays.toString(values);
}
}
sb.append(next.getKey()).append("=").append(value).append("&");
}
if (sb.length() > 0) {
bodyString = sb.toString().substring(0, sb.toString().length() - 1);
}
return bodyString;
} else {
return IOUtils.toString(request.getInputStream());
}
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes());
return new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public int read() {
return bais.read();
}
@Override
public void setReadListener(ReadListener readListener) {
}
};
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。