如果没有文件上传,可以写一个包装器
package dry.framework.service;
import dry.base.service.StreamService;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class RequestWrapperService extends HttpServletRequestWrapper {
private String body;
public RequestWrapperService(HttpServletRequest request) {
super(request);
try {
body = new String(StreamService.readStream(request.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public String getBody() {
return this.body;
}
@Override
public ServletInputStream getInputStream() {
final ByteArrayInputStream is = new ByteArrayInputStream(body.getBytes());
return new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
@Override
public int read() {
return is.read();
}
};
}
@Override
public BufferedReader getReader() {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
}
然后在过滤器里面这样返回改写的请求对象
chain.doFilter(new RequestWrapperService(r), response);
如果有文件上传,把文件流存成字符串不合适吧,该怎么写呢?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…