-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! "

6
  • 1
    Can I ask why you're trying to work around the standard ways of acquiring a HttpServletResponse? Commented Mar 21, 2012 at 12:15
  • Because I don't like the standard way? :) Commented Mar 21, 2012 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... Commented Mar 21, 2012 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. Commented Mar 21, 2012 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. Commented Mar 21, 2012 at 12:25

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, an interceptor will do it, although not ideal :S
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.