user4577362
user4577362

Reputation:

Autowiring HttpServletRequest in Spring controller

Let's say I have a Spring controller.

@RequestMappin("/path")
public MyController {
}

As stated, default scope of the controller is Singleton. I know that I can autowire request in REQUEST scope beans, however, if I try to autowire request, so that

@RequestMappin("/path")
public MyController {
        @Autowired
        private HttpServletRequest request;
    }

It still works, and for each request I get appropriate request object. Does it mean that autowire works regardless the scope is request or not?

Upvotes: 9

Views: 12281

Answers (4)

august0490
august0490

Reputation: 874

If you don't want to use @Autowired you can get HttpServletRequest in this way:

HttpServletRequest request = 
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();

Upvotes: 0

neo
neo

Reputation: 350

When a spring web based application bootstraps, it will register the bean of type ServletRequest,ServletResponse,HttpSession,WebRequest with the support of ThreadLocal variables. So whenever you request one kind of above four, the actual value will be the actual stored ThreadLocal variable that are bound to the current thread.

You can find the details implementation mechanisms of @Autowired HttpServletRequest at @Autowired HttpServletRequest

Upvotes: 10

piotrek
piotrek

Reputation: 14550

if it works that means spring doesn't inject exactly http request but a proxy. the proxy delegates calls to current http request

Upvotes: 10

Efe Kahraman
Efe Kahraman

Reputation: 1438

You can get HttpServletRequest object in each webservice method. Such as:

@RequestMapping("/method")
public void method(HttpServletRequest req) {
   // ...
}

Upvotes: 2

Related Questions