Reputation: 48634
If you have a Spring-MVC @Controller
for an HTML form and
Validator
for the command object of the formBindingResult
given to your request handler hasErrors()
.What HTTP status code does the reply to the client have? Is it 400 (Bad Request), as we might expect for a RESTful service? That is, does Spring examine the BindingResult
and use the presence of errors to set the status code?
Sample code:
@Controller
public class MyController {
public static class Command {
...
}
public static final String COMMAND = "command";
public static final String FORM_VIEW = "view";
private Validator formValidator = ...
@RequestMapping(value = { "myform" }, method = RequestMethod.POST)
public String processAddCheckForm(
@ModelAttribute(value = COMMAND) @Valid final Command command,
final BindingResult bindingResult) {
if (!bindingResult.hasErrors()) {
// Do processing of valid form
return "redirect:"+uri;
} else {
return FORM_VIEW;
// What status code does Spring set after this return?
}
}
@InitBinder(value = COMMAND)
protected void initAddCheck(WebDataBinder binder) {
binder.addValidators(formValidator);
}
}
Upvotes: 0
Views: 1791
Reputation: 168
If one uses eg. ajax to make calls to spring mvc controller and status 400 is required after failed validation, one could use ModelAndView. ModelAndView allows to change status code of response:
if (bindingResult.hasErrors()) {
ModelAndView modelAndView = new ModelAndView("template", "entity", entity);
modelAndView.setStatus(HttpStatus.BAD_REQUEST);
return modelAndView;
}
Upvotes: 0
Reputation: 48634
The status code is, perhaps surprisingly, not 400 (Bad Request), but 200 (OK).
This is presumably to ensure that the user's web browser will display the form with its error messages, rather than a generic 400 (Bad Request) error page. However, Firefox seems OK if you have your request handler sets the status code to 400 for this case.
Upvotes: 1