自定义MyHttpServletRequest解决过滤器拦截@RequestBody整体JSON请求问题

时间:2022-12-01 13:49:56
package information;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.springframework.util.StreamUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {

private byte[] requestBody = null;

// 传入是JSON格式 转换成JSONObject
public JSONObject getRequestBody() throws UnsupportedEncodingException {
return JSON.parseObject((new String(requestBody, "UTF-8")));
}

public void setRequestBody(JSONObject jsonObject) throws UnsupportedEncodingException {
this.requestBody = jsonObject.toJSONString().getBytes("UTF-8");
}

public MyHttpServletRequestWrapper(HttpServletRequest request) {

super(request);

try {
requestBody = StreamUtils.copyToByteArray(request.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}

@Override
public ServletInputStream getInputStream() throws IOException {
if (requestBody == null) {
requestBody = new byte[0];
}
final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody);
return new ServletInputStream() {
@Override
public int read() throws IOException {
return bais.read();
}

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

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

@Override
public void setReadListener(ReadListener listener) {

}
};
}

@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
}

  代码如上。

  自定义过滤器拦截到作为一个整体的JSON格式的请求以后,如果要读取内容就必须调用request.getInputStream()获取输入流来读取。但是这个方法在定义的时候因为不能调用reset方法,所以实际上调用一次以后,流读取到了结束无法再次读取,导致以后的请求无法获取到参数。

  这里使用了一个自定义的HttpServletRequest来保存一下请求的内容,之后doChain连锁把这个丢进去就好了。

  封装了JSONObject的转换,直接调用对应方法就可以修改请求参数内容了。

 

  参考:http://huangqiqing123.iteye.com/blog/2237263