I am using spring framework 3. I have a form for posting comments to the article. When the form is submitted, it is checked if there any errors. In case there is no errors, cont
bkent314 is right:
Have a look at this two method that is a way that defently works. I separate domain objects from form gui objects (FolderCreateCommand) but that is my style. And in this case I use ModelAndView for return instead of string, because so I have full controll to the model.
@RequestMapping(method = RequestMethod.GET, params = "form")
public ModelAndView createForm() {
return modelAndViewForCreate(new FolderCreateCommand(..default values..));
}
@RequestMapping(method = RequestMethod.POST)
public ModelAndView create(@Valid FolderCreateCommand folderCreateCommand,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return modelAndViewForCreate(folderCreateCommand);
}
Folder folder = this.folderService.createFolder(folderCreateCommand);
return redirectToShow(folder);
}
private ModelAndView modelAndViewForCreate(FolderCreateCommand folderCreateCommand) {
ModelMap uiModel = new ModelMap();
uiModel.addAttribute("folderCreateCommand", folderCreateCommand);
uiModel.addAttribute("parentFolders", this.folderDao.readAll());
return new ModelAndView("folders/create", uiModel);
}
private ModelAndView redirectToShow(Folder folder) {
return new ModelAndView(new RedirectView("/folders/" + folder.getId(), true));
}
Try using the view of the page of the "add comment" form instead of redirecting to the view that displays the new comment:
if(result.hasErrors()) {
return "commentForm";
}
You may also have to add @ModelAttribute Comment
in the method signature...
The display of errors in <form:errors path="author"/>
works like this:
Errors
are saved as an attribute in the HttpServletResponse
objectresponse.getAttribute(name)
to find the Errors
instance to displayWhen you use redirect:url
, you are instructing Spring to send a 302 Found
to the client's browser to force the browser to make a second request, to the new URL.
Since the redirected-to page is operating with a different set of request/response objects, the original Errors
is lost.
The simplest way to pass "errors" to a page you want to redirect to in order for the new page to display it would be to handle it yourself, by adding a message to the Session
object which the second page's controller can look at (or by passing an argument in the URL).