3

How can I access the response object from a bean? To get the request object I use the following.

    ServletRequestAttributes attr = (ServletRequestAttributes) 
        RequestContextHolder.currentRequestAttributes();

Is there something similar to the above for response object?

Viren Pushpanayagam
  • 2,397
  • 6
  • 35
  • 39
  • 1
    Check Bozho's answer here: [enter link description here](http://stackoverflow.com/a/6984252/433789 "@Autowired HttpServletResponse") – sdouglass Jun 04 '12 at 22:01

1 Answers1

5

If you are in a web application context (which it looks like you are) you can auto wire in the HttpServletRequest or HttpServletResponse.

The request/response from the current request scope will be injected.

@Component
public class SomeComponentInAWebApplicationContext {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    ...
}
Rob Beardow
  • 871
  • 5
  • 6
  • 3
    I see that the answer has been accepted, but I'm unclear on this could work - where in Spring are these dependencies injected from? Trying it out, it fails as expected: Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [javax.servlet.http.HttpServletResponse] found for dependency. Am I missing something? – Eugen Dec 28 '11 at 12:42
  • 1
    The component must be part of a WebApplicationContext i.e. one started from a -servlet.xml context. – Rob Beardow Oct 01 '12 at 23:29
  • Request and response will be wired only once. – madhead Jan 21 '13 at 15:46