请问在springmvc中非controller中如何获取request对象

_沉浮_ 2015-06-02 10:17:43
因为现在有一需求,在接口中写方法获取 ip,port appname,根据以往情况看只有request对象才有这能力,但是一般只有继承与servlet的类中才能获取这个对象,在网上查了,
@Autowired(required=true)  
private HttpServletRequest request;
这可以获取request,但是在调用此接口对应的方法是,出现了异常,
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
之后继续查,发现好像是因为spring的对象都是单例,再次注入就出现了这个问题,那么问题又回到了怎么获取request对象,或者有什么其他的方法获取访问项目的地址呢?
...全文
2607 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
kusedexingfu 2017-10-27
  • 打赏
  • 举报
回复
6楼正解 HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
iamjsber 2016-07-11
  • 打赏
  • 举报
回复
引用 1 楼 Mrzhang__ 的回复:
HttpServletRequest request = ServletActionContext.getRequest();
瞎鸡巴写 傻比
fpf19910417 2015-06-05
  • 打赏
  • 举报
回复
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
南轲梦 2015-06-05
  • 打赏
  • 举报
回复
在 Controller 中通过方法入参获取 request对象,再将request对象传入普通接口
_沉浮_ 2015-06-02
  • 打赏
  • 举报
回复
引用 1 楼 Mrzhang__ 的回复:
HttpServletRequest request = ServletActionContext.getRequest();
普通方法,什么都不继承,什么都不实现,ServletActionContext 获取不到的
_沉浮_ 2015-06-02
  • 打赏
  • 举报
回复
引用 2 楼 baidu_28673573 的回复:
吧request放到threadlocal中,或者作为参数传递
就算作为参数,但是在普通方法中怎么获取request作为参数呢?
baidu_28673573 2015-06-02
  • 打赏
  • 举报
回复
吧request放到threadlocal中,或者作为参数传递
老年张三丰 2015-06-02
  • 打赏
  • 举报
回复
HttpServletRequest request = ServletActionContext.getRequest();

81,094

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧