3

I have :

@Controller
@RequestMapping(value="admin/*", method=RequestMethod.GET)
public class AdminController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @RequestMapping
    public ResponseEntity<String> test0() {
        System.out.println("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ");
        return null;
    }


}

and the tag:

<mvc:annotation-driven />

in my config.xml

It should be enough I feel, but there is a problem with @Autowired:

No matching bean of type [javax.servlet.http.HttpServletResponse] found for dependency: expected at least 1 bean which qualifies ...

I have seen a couple of solutions mention setting up beans and such, but I am sure there has to be some better way. The annotation-scan should take care of this. It would suck if I have to set up beans in xml for several different annotations at different times. I just want the annotations to work when I use them!

I have seen: Spring MVC - Response

Thanks!

Community
  • 1
  • 1
mjs
  • 21,431
  • 31
  • 118
  • 200
  • Possible duplicate: http://stackoverflow.com/questions/6984054/autowired-httpservletresponse – Kevin Mar 15 '12 at 14:41

3 Answers3

3

As a workaround try:

@RequestMapping
public ResponseEntity<String> test0(
        HttpServletRequest request, 
        HttpServletResponse response) {
    System.out.println("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ");
    return null;
}

Also try adding RequestContextListener but this should't be required in Spring MVC environment.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • @momomo it actually shows me the same error, but still works. What was your solution concerning to this part? Does it really needs an update per Request? if so why the Request does not need the same? – X-HuMan Apr 24 '19 at 21:03
3

Autowiring doesn't work for the response, only the request. There are workarounds, but they're kind of hacky and lame. I ran into the same issue, here's my original question with a link to the workaround: @Autowired HttpServletResponse

Community
  • 1
  • 1
Kevin
  • 24,871
  • 19
  • 102
  • 158
  • 1
    I can let people know that the way I solved this finally was using an Interceptor on "*" and setting the response from there on the request .... making it available through the request, which is autowirable ... – mjs Jul 24 '13 at 09:55
1

It does not work as you want it, as fields, because a request and respose changes after each request (in lack of better explanation). You cannot reinject every time the new request/response in the fields. That is why you have to add them in the method where they will be injected every time new.

AdrianS
  • 1,980
  • 7
  • 33
  • 51