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.

Tags: , , ,