Spring实现在非controller中获取request对象

网友投稿 732 2022-12-15

Spring实现在非controller中获取request对象

Spring实现在非controller中获取request对象

目录在非controller中获取request对象首先在web.xml中添加一个-然后在程序中就可以使用非controller层获取responseuLtcTkDMs和request对象如下所示

在非controller中获取request对象

在Controller中,我们可以直接在参数中加上HttpServletRequest request,springMVC就会自动将request绑定进参数,而如果我们想在其他地方获取request就要如下这么做了。

首先在web.xml中添加一个-

针对request级别的,要和ContextLoaderListener区分开

org.springframework.web.context.request.RequestContextListener

然后在程序中就可以使用

如下的代码来获取request对象了

HttpServletRequest request=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

其实背后的原理就是将这个request对象存在ThreadLocal线程变量里面。

非controller层获取response和request对象

如下所示

ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

HttpServletResponse response = attrs.getResponse();

HttpServletRequest request = attrs.getRequest();

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:springSecurity之如何添加自定义过滤器
下一篇:使用springmvc的controller层获取到请求的数据方式
相关文章

 发表评论

暂时没有评论,来抢沙发吧~