-1

See related: Accessing HttpServletRequest object in a normal Java class from Spring

Note, this one is about RESPONSE...

"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 HttpServletResponse object in a method.

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

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

Preferably non application server dependent way. have a normal Java class in a Spring MVC 3.06 web application.

Thanks! "

Community
  • 1
  • 1
mjs
  • 21,431
  • 31
  • 118
  • 200
  • 1
    Can I ask why you're trying to work around the standard ways of acquiring a `HttpServletResponse`? – Paul Grime Mar 21 '12 at 12:15
  • Because I don't like the standard way? :) – mjs Mar 21 '12 at 12:18
  • I see no reason why I should force the developer to keep passing these things in, when you can acquire them for no cost in a different way. Plus, there are places in the code where you don't neccessarly have the request or response at hand... – mjs Mar 21 '12 at 12:19
  • 1
    If you don't have the request or response to hand, then it could be argued that you're accessing it/them from the wrong place. – Paul Grime Mar 21 '12 at 12:21
  • 1
    I am sure you could argue that, yes... But then again, the same argument would have been heard back in older jee and spring versions about various other things, that annotations is not needed to resolve controllers, entities, etc because you can define them in an xml config file. If there is no reason to why it could not be simpler, why not make it simpler? Code is made cleaner by having less cludd. – mjs Mar 21 '12 at 12:25
  • Guess you could probably mirror this filter and store the response somewhere - http://grepcode.com/file/repo1.maven.org/maven2/org.springframework/spring-web/3.0.7.RELEASE/org/springframework/web/filter/RequestContextFilter.java#RequestContextFilter – Paul Grime Mar 21 '12 at 12:52

2 Answers2

1

I think Spring doesn't provide anything for achieving this. But it would be very easy to implement something similar as RequestContextFilter and RequestContextHolder, but for response object. An equivalent of ServletRequestAttributes probably won't be needed.

sinuhepop
  • 20,010
  • 17
  • 72
  • 107
0

Using @ResponseBody annotation you can send the methods return value directly into your response.

Stefan
  • 12,108
  • 5
  • 47
  • 66