开发者

Access Spring MVC BindingResult from within a View

I'm looking for a way to access a BindingResult from within the view (in my case a JSP page).

I have the following controller method:

@RequestMapping(value="/register/accept.html"开发者_开发百科,method=RequestMethod.POST)
public ModelAndView doRegisterAccept(
  @Valid @ModelAttribute("registrationData") RegistrationData registrationData,
  BindingResult bindingResult
) {

  ModelAndView modelAndView         = new ModelAndView();
  modelAndView.addObject("bindingResultXXX", bindingResult);
  modelAndView.setViewName("users/registration/register");
  return modelAndView;

}

When executing this, the RegistrationData get's populated and the errors are stored in the BindingResult. So far, so good. However, I do have to add the BindingResult manually into the ModelAndView for it to become visible within the View.

Is there a way to automatically add the BindingResult into the model? I already tried adjusting the method signature to

public ModelAndView doRegisterAccept(
  @Valid @ModelAttribute("registrationData") RegistrationData registrationData,
  @ModelAttribute("bindingResult") BindingResult bindingResult
) {

where I was hoping - as any other parameter - the BindingResult would get added into the model under the key bindingResultbut unfortunately that's not working.

So, any ideas?

Addition

I just found that the results indeed get published using the key

org.springframework.validation.BindingResult.<NAME_OF_MODEL_ATTRIBUTE>

so I suppose just adding it under the plain name is not encouraged by the Spring guys?!


You have to add "errors" tag in your form view, as described here : http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/view.html#view-jsp-formtaglib-errorstag. Then in your Controller, you just put a test :

if(bindingResult.hasErrors()) {
   ... display your form page again 
   (and "errors" tags will be populated by validation messages corresponding to each field) ...
}
else {
   ... here, you know that your RegistrationData is valid so you can treat it (save it I guess) ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜