Spring实现在非controller中获取request对象
更新时间:2021年08月26日 11:00:59 作者:虎哥和你一起学编程
这篇文章主要介绍了Spring实现在非controller中获取request对象方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
在非controller中获取request对象
在Controller中,我们可以直接在参数中加上HttpServletRequest request,springMVC就会自动将request绑定进参数,而如果我们想在其他地方获取request就要如下这么做了。
首先在web.xml中添加一个监听器
针对request级别的,要和ContextLoaderListener区分开
<listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener>
然后在程序中就可以使用
如下的代码来获取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();
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
java中ThreadLocal和ThreadLocalMap浅析
这篇文章主要介绍了java中ThreadLocal和ThreadLocalMap浅析,ThreadLocal类用来设置线程私有变量 本身不储存值 主要提供自身引用 和 操作ThreadLocalMap 属性值得方法,需要的朋友可以参考下2023-09-09Spring Boot 3.1中整合Spring Security和Keycloak的方法
本文介绍在最新的SpringBoot3.1版本之下,如何将Keycloak和Spring Security一起跑起来,文中结合实例代码给大家介绍的非常详细,需要的朋友参考下吧2023-06-06elasticsearch集群cluster主要功能详细分析
这篇文章主要为大家介绍了elasticsearch集群cluster主要功能详细分析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-04-04
最新评论