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
?
It is safe for me to assume that I am in a Servlet Context.
Pass it to the constructor: public class XmlParser{ final private HttpServletRequest request; public XmlParser(HttpServletRequest request) { this. request = request; } // use it in othe methods... }
The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet's service methods ( doGet , doPost , etc). String identifier for Basic authentication. String identifier for Client Certificate authentication.
getParameter() − You call request. getParameter() method to get the value of a form parameter.
Assuming you're not able to pass the request object down the call stack, then some kind of sharing mechanism becomes necessary, which is not ideal, but sometimes necessary.
Spring provides the RequestContextFilter for just this purpose. It uses ThreadLocal
, and allows the code to fetch the current request via RequestContextHolder. Note that this filter does not require you to use any other part of Spring:
Servlet 2.3 Filter that exposes the request to the current thread, through both LocaleContextHolder and RequestContextHolder. To be registered as filter in web.xml.
This filter is mainly for use with third-party servlets, e.g. the JSF FacesServlet. Within Spring's own web support, DispatcherServlet's processing is perfectly sufficient.
If you're going to use ThreadLocal
, then better to use an existing, working solution, rather than risk bugs creeping in, which ThreadLocal
code is prone to.
Jon Skeet said practically everything, but one clarification to his advice "just the bits that you need" - if you need your request parameters passed down, but you don't need a dependency on HttpServletRequest
, pass request.getParameterMap()
.
And extending a bit on the ThreadLocal
option - you can have a Filter
which handles all incoming requests, and sets the request in a
public final static ThreadLocal<HttpServletRequest> httpServletRequestTL =
new ThreadLocal<HttpServletRequest>();
Because you are setting it on each request (careful with the filter mapping), you won't have to worry about the servlet-container thread pool - you will always have the current request.
P.S. this is the logic behind the spring utility proposed by skaffman - I join him recommending the stable component, rather than making your own.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With