Java拦截器读取请求主体使请求为空 [英] Java interceptor reading request body makes the request empty

查看:270
本文介绍了Java拦截器读取请求主体使请求为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用spring编写了一个拦截器,该拦截器在preHandle方法中从HTTPServletRequest读取请求主体.请求正文包含json.我也能够读取请求正文,但是请求对象发生了某些事情,请求正文变得空白.并且由于这个请求,它变成了一个不好的请求.任何帮助都感激不尽.预先感谢.

I have written an interceptor using spring that reads the request body from the HTTPServletRequest, in preHandle method. Request body contains json. I am able to read the request body also but something is happening to the request object and the request body is getting blank. And beause of this the request is becoming a bad request. Any help will be much appreciated. Thanks in advance.

推荐答案

我没有使用过JEE拦截器或Spring拦截器,也不知道它们是如何工作的.

I haven't used either JEE interceptors or Spring interceptors and don't know how they work.

但是听起来更简单的方法是使用过滤器(由web.xml配置).由于过滤器是在链中彼此调用的,因此您可以轻松地将转发的HttpServletRequest对象替换为已包装的HttpServletRequest对象(在其中提供主体).

But it sounds like the easier way would be to go with a filter (as configured from the web.xml). Since filters call each other in a chain, you could easily replace the HttpServletRequest object that is forwarded with a wrapped one (where you provide the body).

这可以通过创建您自己的类,扩展 HttpServletRequestWrapper ,然后覆盖适当的方法(getInputStream听起来很像,是吗?).

This could probably be accomplished by creating a class of your own, extending the HttpServletRequestWrapper and then override the appropriate methods (getInputStream sounds like the way to go here, yes?).

您的getInputStream版本将返回您已经阅读的正文的ByteArrayInputStream,或者您认为合适的任何类型的InputStream.

Your version of getInputStream would then return a ByteArrayInputStream of the body you already read, or whatever you kind of InputStream you feel is appropriate.

这篇关于Java拦截器读取请求主体使请求为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆