19

I have a normal Java class in a Spring MVC 3.06 web application.

In this class I would like to inject or get hold of the HttpServletRequest object in a method.

I know I can pass this around, but I was wondering how can I get hold of the request without passing it in to the method. Perhaps using annotations or similar?

Also, what are the "real" concerns with getting hold of the request this way, except some peoples opinions of it being ugly coding. I mean, is it unstable to access it this way?

Preferably non application server dependent way.

I have seen

(HttpServletRequest) RequestContextHolder.getRequestContext().getExternalContext().getNativeRequest() 

but this doesn't seem to work for Spring MVC 3.06 . RequestContextHolder doesn't have the method getRequestContext().

mjs
  • 21,431
  • 31
  • 118
  • 200

2 Answers2

32

Use

((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

I'm not sure where you got RequestContextHolder.getRequestContext(), that's completely wrong.

is it unstable to access it this way?

No, it's stable enough, assuming you're always running the code as part of an HttpServlet request thread. The main issue is that yes, it's ugly, and it makes your code hard to test. That is reason enough not to use it.

If you must use it, then decouple it from your code, e.g.

public void doSomething() {
    HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    doSomething(request);
}

void doSomething(HttpServletRequest request) {
   // put your business logic here, and test this method
}
skaffman
  • 398,947
  • 96
  • 818
  • 769
  • Thanks, yes, perhaps that could create problems when testing, most likely if testing controllers and actions. Decoupling won't really help then, but I have added a static getRequest method that calls a default implementation ( the above ), that can be overriden. Thanks! – mjs Mar 19 '12 at 16:16
  • This worked fine until now :( ... I am trying to reach the from the view using the RequestContextHolder – mjs Sep 30 '12 at 11:33
  • @Anthony You can store aside the response object from the dispatcher or an interceptor – mjs Aug 11 '14 at 19:48
0

@Context HttpServletRequest httpServletRequest =null;

use this

user3465058
  • 41
  • 1
  • 7