Autowiring HttpServletRequest in Spring controller
Asked Answered
T

4

9

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?

Tetragrammaton answered 20/2, 2015 at 22:0 Comment(1)
Does this request is thread safe? I mean if there are attributes in this request , the value of the attribute is unique?Orta
X
10

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

Xeroderma answered 20/2, 2015 at 22:13 Comment(2)
So is this default behaviour, or with Reques scoped beans it injects request directly?Tetragrammaton
i don't know. but it really should not matter - your program shouldn't rely on thatXeroderma
E
10

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

Excepting answered 20/9, 2018 at 6:6 Comment(1)
is it the reason we can do as following, to get the ServletRequest in an auto-wired bean to a controller like below? @Component public class PageModel { private HttpServletRequest request; public PageModel(HttpServletRequest request) { this.request = request; } if it works that means spring doesn't inject exactly http request but a proxy. the proxy delegates calls to current http request?Afflatus
V
2

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

@RequestMapping("/method")
public void method(HttpServletRequest req) {
   // ...
}
Venicevenin answered 20/2, 2015 at 22:8 Comment(0)
S
0

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

HttpServletRequest request = 
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
Sufficient answered 29/3, 2022 at 15:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.