从Java代码获取HttpServletRequest(请求)对象 [英] Get the HttpServletRequest (request) object from Java code

查看:279
本文介绍了从Java代码获取HttpServletRequest(请求)对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Java代码中获取请求对象。出于某些原因,我无法将此对象传递给我的代码。有什么方法我可以这样说: getCurrentHTTPServletRequest

I need to get hold of the request object in Java code. I can't pass this object down to my code for certain reasons. Is there any way I can say something like: getCurrentHTTPServletRequest?

我可以安全地假设我是在Servlet上下文中。

It is safe for me to assume that I am in a Servlet Context.

推荐答案

如果您需要,将其传递下去。你做的其他事情基本上都是丑陋的。

Well you should pass it down if you need it. Anything else you do is going to be ugly, basically.

可以使用 ThreadLocal 变量 - 基本上设置上下文当您收到请求时,该特定线程,然后稍后获取它。只要您只需要处理正在处理它的线程中的请求,并且只要您不进行任何时髦的异步请求处理,这将起作用。但是,正是由于这些原因,它很脆弱。

You could use a ThreadLocal variable - basically set the context for that particular thread when you get the request, and then fetch it later on. That will work so long as you only need to get at the request within the thread that's processing it - and so long as you don't do any funky asynchronous request handling. It's brittle though, for precisely those reasons.

但是,我强烈建议你明确你的依赖关系。要么传递servlet请求,要么只传递你需要的位。

However, I would strongly advise you to be explicit about your dependencies instead. Either pass the servlet request down, or just the bits that you need.

这篇关于从Java代码获取HttpServletRequest(请求)对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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