大佬教程收集整理的这篇文章主要介绍了一次读取后,Http Servlet请求会丢失POST正文中的参数,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
顺便说一句,解决此问题的另一种方法是不使用筛选器链,而是使用可以在已解析请求主体上运行的方面来构建自己的拦截器组件。由于您只需将请求inputStream
转换为自己的模型对象一次,这样做也可能会更有效率。
但是,我仍然认为要多次读取请求正文是合理的,尤其是在请求通过过滤器链移动时。通常,我会将过滤器链用于要保留在http
层的某些操作,这些操作与服务组件分离。
正如Will Hartung
所建议的那样,我是通过扩展httpServletrequestWrapper
,使用请求inputStream
并实质上缓存字节来实现的。
public class MultiReadhttpServletrequest extends httpServletrequestWrapper {
private ByteArrayOutputStream cachedBytes;
public MultiReadhttpServletrequest(httpServletrequest request) {
super(request);
}
@OverrIDe
public ServleTinputStream geTinputStream() throws IOException {
if (cachedBytes == null)
cacheinputStream();
return new CachedServleTinputStream();
}
@OverrIDe
public BufferedReader getReader() throws IOException{
return new BufferedReader(new inputStreamReader(geTinputStream()));
}
private voID cacheinputStream() throws IOException {
/* Cache the inputstream in order to read it multiple times. For
* convenIEnce, I use apache.commons I@R_262_9981@ls
*/
cachedBytes = new ByteArrayOutputStream();
I@R_262_9981@ls.copy(super.geTinputStream(), cachedBytes);
}
/* An inputstream which reads the cached request body */
public class CachedServleTinputStream extends ServleTinputStream {
private ByteArrayinputStream input;
public CachedServleTinputStream() {
/* create a new input stream from the cached request body */
input = new ByteArrayinputStream(cachedBytes.toByteArray());
}
@OverrIDe
public int read() throws IOException {
return input.read();
}
}
}
现在,通过在过滤器链中传递原始请求之前,可以包装原始请求多次读取请求主体:
@H_696_18@public class MyFilter implements Filter {
@OverrIDe
public voID doFilter(Servletrequest request, ServletResponse response,
FilterChain chain) throws IOException, servletexception {
/* wrap the request in order to read the inputstream multiple times */
MultiReadhttpServletrequest multiReadrequest = new MultiReadhttpServletrequest((httpServletrequest) request);
/* here I read the inputstream and do my thing with it; when I pass the
* wrapped request through the filter chain, the rest of the filters, and
* request handlers may read the cached inputstream
*/
domyThing(multiReadrequest.geTinputStream());
//OR
anotherUsage(multiReadrequest.getReader());
chain.doFilter(multiReadrequest, responsE);
}
}
该解决方案还将允许您通过这些getParameterXXX方法多次读取请求正文,因为底层调用是geTinputStream()
,当然,它将读取缓存的请求inputStream
。
编辑
对于较新版本的ServleTinputStream
界面。您需要提供其他一些方法的实现,例如isReady
,setReadListener
等等。请参考下面的注释中提供的问题。
以上是大佬教程为你收集整理的一次读取后,Http Servlet请求会丢失POST正文中的参数全部内容,希望文章能够帮你解决一次读取后,Http Servlet请求会丢失POST正文中的参数所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。