Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a static way to get the current HttpServletRequest in Spring

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.

like image 367
Spring Monkey Avatar asked Feb 26 '09 19:02

Spring Monkey


People also ask

How do I get HttpServletRequest in Spring?

HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder. getRequestAttributes()) . getRequest(); Solution 2: inside bean (supported by >= 2.5, Spring 3.0 for singelton beans required!)

How do I get HttpServletRequest in Webflux?

The code to get it is as follows. ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder. getRequestAttributes(); // get the request HttpServletRequest request = requestAttributes. getRequest();

Can we Autowire HttpServletRequest?

Request-scoped beans can be autowired with the request object. Warning for Spring <=3.1 users the autowiring will not work running tests.

What is the use of HttpServletRequestWrapper?

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.


1 Answers

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; } 
like image 68
Abbadon Avatar answered Oct 12 '22 22:10

Abbadon