java 从视图中访问 Spring MVC BindingResult
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6704478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access Spring MVC BindingResult from within a View
提问by perdian
I'm looking for a way to access a BindingResult
from within the view (in my case a JSP page).
我正在寻找一种BindingResult
从视图中访问 a 的方法(在我的例子中是一个 JSP 页面)。
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.
执行此操作时,将RegistrationData
填充 get 并将错误存储在BindingResult
. 到现在为止还挺好。但是,我必须BindingResult
手动将其添加到ModelAndView
其中才能在视图中可见。
Is there a way to automaticallyadd the BindingResult
into the model? I already tried adjusting the method signature to
有没有办法自动添加BindingResult
到模型中?我已经尝试将方法签名调整为
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 bindingResult
but unfortunately that's not working.
我希望 - 作为任何其他参数 -BindingResult
将被添加到密钥下的模型中,bindingResult
但不幸的是这不起作用。
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?!
所以我想只是在普通名称下添加它不会受到 Spring 家伙的鼓励吗?!
回答by Mathieu L
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 :
您必须在表单视图中添加“错误”标签,如下所述:http: //static.springsource.org/spring/docs/3.0.5.RELEASE/reference/view.html#view-jsp-formtaglib-errorstag. 然后在您的控制器中,您只需进行测试:
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) ...
}