我刚也找到了一种解决办法:
先定义一个类包含一个body域用于存储request.getInputStream()的内容,继承自HttpServletRequestWrapper,并且覆盖它的getInputStream()方法。
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper{
private final byte[] body;
public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
body = Streams.readBytes(request.getInputStream());
}
@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();
}
};
}
}
然后在filter里面替换掉actionContext里面的request
try {
requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
actionContext.setRequest((HttpServletRequest) requestWrapper);
payload = Json.toJson(Json.fromJson(Streams.utf8r(requestWrapper.getInputStream())));
} catch (IOException e) {
e.printStackTrace();
return new UTF8JsonView(JsonFormat.compact()).setData(Result.doError(106,"failed to get the request body."));
}