springservletsspring-mvc

Can a Spring MVC controller return both a HttpServletResponse and a view?


My existing code is like:

String myController(@PathVariable someId, ModelMap map){
....
return "myViewName";
}

Now I want to set a cookie in some cases, so I need to get hold of a HttpServletResponse obj. Can I just add such a response obj to the list of params and operate on it in the controller? If so, I wonder how my own response is kind of reconciled with the response generated by the JSP that resolves the "myViewName".


Solution

  • Yes.

    @RequestMapping
    public String myController(@PathVariable someId, ModelMap map, HttpServletResponse response) {
        // Do what you need to do on the response, like set a cookie
        return "myViewName";
    }