Reputation: 138
In Spring MVC @RequestMapping annotation, I am returning JSP page name as result. This returns HTTP status code 200 OK. How can I change this status code to something like 201 created ?
@ResponseStatus doesn't work. Also, HttpServletResponse won't work since I need to return my custom JSP page only.
@RequestMapping(method = RequestMethod.POST)
public String addPhone(@ModelAttribute("phone") Phone phoneVO) {
phoneManager.addPhone(phoneVO);
return "redirect:/phone";
}
Upvotes: 3
Views: 12190
Reputation: 674
For those of you that wants to set a status returning a model object like me:
@RequestMapping(value = "/yourRoute", method = RequestMethod.POST)
public ModelAndView accountsPagePOST(@RequestBody final String body)
{
ModelAndView model = new ModelAndView("yourView");
//TODO do your logic and add your objects
model.setStatus(HttpStatus.OK);
return model;
}
Hope this helps someone... You can obviously set a failed status in case something goes wrong.
Upvotes: 9
Reputation: 138
Ok, I found the solution:
response.setStatus(HttpServletResponse.SC_CREATED);
return "phonePage";
As mentioned by @SotiriosDelimanolis, the redirect was overwriting the value in setStatus. So, instead of redirect, I am calling the JSP page directly (while also re-sending the parameters).
I guess with redirect, the status has to be HTTP OK.
Upvotes: 0
Reputation: 3820
You should try doing following, you should return your view name instead without any redirect, the spring view resolver should do the needful to resolve your custom jsp. (You should configure view resolver properly)
@RequestMapping(method = RequestMethod.POST)
public String addPhone(@ModelAttribute("phone") Phone phoneVO, HttpServletResponse response) {
phoneManager.addPhone(phoneVO);
response.setStatus(HttpServletResponse.SC_CREATED);
return "phone";
}
Other option could be using @ResponseStatus annotation on your handler method itself as it is certain that the responsibility of addPhone is to create a new resource on server. Hence you could define on handler method the status.
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public String addPhone(@ModelAttribute("phone") Phone phoneVO, HttpServletResponse response) {
phoneManager.addPhone(phoneVO);
return "phone";
}
Upvotes: 3
Reputation: 1
@RequestMapping(method = RequestMethod.POST)
public String addPhone(@ModelAttribute("phone") Phone phoneVO) {
phoneManager.addPhone(phoneVO);
return "/phone";
}
Oops, sent before I was finished. Intended to write that you can add HttpServletResponse as a parameter and then use it to set the code.
Upvotes: -2