I am using Spring annotations, I can pass the HttpRequestContext
from the Controller to the Service.
I am looking for a static way or any better solution than passing RequestContext
around.
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder. getRequestAttributes()) . getRequest(); Solution 2: inside bean (supported by >= 2.5, Spring 3.0 for singelton beans required!)
The code to get it is as follows. ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder. getRequestAttributes(); // get the request HttpServletRequest request = requestAttributes. getRequest();
Request-scoped beans can be autowired with the request object. Warning for Spring <=3.1 users the autowiring will not work running tests.
Class HttpServletRequestWrapper. Provides a convenient implementation of the HttpServletRequest interface that can be subclassed by developers wishing to adapt the request to a Servlet. This class implements the Wrapper or Decorator pattern. Methods default to calling through to the wrapped request object.
If you are using spring you can do the following:
public static HttpServletRequest getCurrentHttpRequest(){ RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); if (requestAttributes instanceof ServletRequestAttributes) { HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest(); return request; } logger.debug("Not called in the context of an HTTP request"); return null; }
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