I've tried a lot to implement a validation inside a MultiActionController and it seems it's not plain sailing. I need to validate a form and, in case of failure, I want to redirect to the same form, displaying the errors and also being able to load some info from a database. So basically I have this:
@RequestMapping("/addResponse.htm")
public ModelAndView addResponse(@ModelAttribute("responseDTO") ResponseDTO
respDTO, BindingResult result, HttpServletRequest request) {
ResponseFormValidator respValidator = new ResponseFormValidator();
respValidator.validate(respDTO, result);
if (result.hasErrors()) {
return new ModelAndView("redirect:responseForm.htm?id=" + respDTO.getProjID());
}
}
What I want is for the responseForm handler method to remember the errors resulted from the validation process (the Result Object) Of course, I can copy and paste the logic fr开发者_开发问答om that method inside my if statement but I'm thinking it must be a better way than just copy and paste.
Any help will be highly appreciated!
In Spring version prior to 3.1.x, if you want to pass object through a redirect, you have to make your controller "session" aware. http://static.springsource.org/spring/docs/2.5.x/reference/portlet.html#portlet-controller (part 16.9, look for @SessionAttribute)
But after it is your responsibility to clean the object(s) stored in session that you do not want to use anymore.
With Spring 3.1.x, the flashAttribute is a very useful mecanism and Spring does the job for that.
http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-flash-attributes
Hereunder a little code to show the principle:
@RequestMapping(value = "form", method = RequestMethod.GET)
public String showForm(@ModelAttribute("form") FormBean formBean) {
// Set some properties if needed
return "tiles-litools-mml";
}
@RequestMapping(value = "form", method = RequestMethod.POST)
public String formAction( @Validated({MyValidator.class})
@ModelAttribute("form") FormBean formBean,
BindingResult validatorresult, Model model, Errors errors,
RedirectAttributes redirectAttributes) {
//redirect if any error
if (validatorresult.hasErrors()){
redirectAttributes.addFlashAttribute("message", "MML session failed");
redirectAttributes.addFlashAttribute("form", formBean);
redirectAttributes.addFlashAttribute("validation", validatorresult);
return "redirect:/app/tools/form"; // redirect to the form GET method
}
// TODO continue code for process the form (valid!)
}
I assume you do not extends MultiActionController.
精彩评论