Can Spring MVC return HttpServletResponse and view?

My existing code is similar:

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

Now I want to set a cookie in some cases, so I need to get the HttpServletResponse obj object. Can I add such an obj answer to the parameter list and work with it in the controller? If so, I wonder how my own answer came to terms with the answer created by the JSP, which resolves to "myViewName".

+6
source share
2 answers

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"; } 
+9
source

Regarding your other question: "how is my own answer a little reconciled with the answer created by the JSP that resolves" myViewName ".

When you return the view "myViewName", it will be allowed for a specific resource (JSP View or JSON View or any other kind). As soon as this view resource is received depending on what you return, this view renders a response. This response object is the same as passed to the controller function (myController). Tell me, if you set some cookies / response headers in the controller function, the response that the view uses to render will also have the same properties.

If you want to handle the actual rendering / response yourself, you can always get the response output stream and write to it and close the stream. Then, the view you return is simply ignored, because the dispatcher checks that the response has already been processed and will simply process the messages.

Hope this clears up for anyone looking for dispatcher logic.

0
source

Source: https://habr.com/ru/post/957088/


All Articles