I have a confession to make. I created this blog to not only help people out, or opine about industry topics, but as a personal scratch pad for me to help remember stuff. So with that in mind, I am going to take a personal note of a problem I had been dealing with.
Most of us using Spring MVC are familiar with the following:
class SomeController {
@RequestMapping("/action")
public void action(HttpServletRequest request) {
// do something
}
}
Simple, right? Annotation-mapped controller which will use the RequestMapping annotation to determine the viewName. Confused? Check this out. But, what happens when you decide to set a cookie in the action method? For this we will need access to the HttpServletResponse object. No problem, since Spring will automagically inject it into our method.
Observe the following:
class SomeController {
@RequestMapping("/action")
public void action(HttpServletRequest request, HttpServletResponse response) {
// add cookie using response.setCookie(Cookie) method
}
}
Looks good to me. Only problem is, it will not work (a small problem). Apparently, the Spring Framework assumes you are handling the response if it passes it into a method with a return type of void. This is because there is no good way for it to know if you did or didn’t.
No big deal, we can use a string to prevent this behavior:
class SomeController {
@RequestMapping("/action")
public String action(HttpServletRequest request, HttpServletResponse response) {
// add cookie using response.setCookie(Cookie) method
return "action";
}
}
This will fix the problem. Consult the documentation here for more information.
s


#1 by Nishant Sonar at August 4th, 2010
| Quote
This is a good note from your side , thanks for sharing this information.
I was actually doing the same stuff and now i wonder , how can i send the response object without any view . Did u try this ?
#2 by kerry at August 4th, 2010
| Quote
If you pass in the response, then write nothing to it. What happens?
#3 by michael at November 23rd, 2010
| Quote
Hi dear Kerry.
after googling i found your article and be happy cause i think that my problem gonna be solve.
but either not any full example or correct link exist.
please help me
#4 by kerry at November 23rd, 2010
| Quote
I’ll send you an email to see if I can help.