【发布时间】:2012-05-07 09:42:00
【问题描述】:
我正在查看sitebricks here 中HiddenMethodFilter 的实现:
在第 65 行有以下代码:
try {
String methodName = httpRequest.getParameter(this.hiddenFieldName);
if ("POST".equalsIgnoreCase(httpRequest.getMethod()) && !Strings.empty(methodName)) {
....
它检查是否设置了特定参数并使用它来包装请求。但是,在读取该参数时,它将消耗流并且最终的 servlet 将无法读取任何数据。
避免这种情况的最佳方法是什么?我实现了 HttpServletRequestWrapper here,它将流的内容读入字节数组。然而,这可能会使用大量内存来存储请求。
private HttpServletRequestWrapper getWrappedRequest(HttpServletRequest httpRequest, final byte[] reqBytes)
throws IOException {
final ByteArrayInputStream byteInput = new ByteArrayInputStream(reqBytes);
return new HttpServletRequestWrapper(httpRequest) {
@Override
public ServletInputStream getInputStream() throws IOException {
ServletInputStream sis = new ServletInputStream() {
@Override
public int read() throws IOException {
return byteInput.read();
}
};
return sis;
}
};
}
有没有更好的方法?我们可以在不消耗流的情况下读取参数吗? (类似于 peek 的东西)我们可以重置流吗?
【问题讨论】:
标签: java servlets servlet-filters