当基于 spring3 注解的控制器中表单验证失败时,参考数据会丢失
我正在做基于 spring 3 注解的控制器的事情。问题是,当验证失败时,参考数据就会丢失,即countryDivisions 内容。我没有将其放入表单中,因为它不是用户可编辑的数据,而这里的正统观念是只有用户可编辑的数据才放入表单中。我还有其他选择吗?
@Controller
public class MyInfoController {
@Autowired
private MyInfoFormValidator validator;
private void loadReferenceData(ModelMap model) {
model.put("countryDivisions",countryDivisionService.getCountryDivisionOrderedByCode());
}
@ModelAttribute
private MyInfoForm loadMyInfo() {
MyInfoForm form = new MyInfoForm();
//load it up
return form;
}
@RequestMapping(value="/editMyInfo", method = RequestMethod.GET)
public String editMyInfo(ModelMap model ) {
loadReferenceData(model);
return "contactEdit";
}
@RequestMapping(value="/editMyInfo", method = RequestMethod.POST)
public String saveMyInfo(ModelMap model, MyInfoForm form,BindingResult result ) {
validator.validate (form,result);
if (result.hasErrors()) {
model.put("commandName", "myInfoForm");
return "contactEdit";
}
//save some stuff
return "redirect:viewMyInfo";
}
}
I'm doing the spring 3 annotation based controller thing. Problem is, when it fails validation, the reference data is lost, namely the countryDivisions stuff. I didn't put it in the form because its not user editable data, and the orthodoxy here is that only user-editable data goes in the form. Do I have any other choice?
@Controller
public class MyInfoController {
@Autowired
private MyInfoFormValidator validator;
private void loadReferenceData(ModelMap model) {
model.put("countryDivisions",countryDivisionService.getCountryDivisionOrderedByCode());
}
@ModelAttribute
private MyInfoForm loadMyInfo() {
MyInfoForm form = new MyInfoForm();
//load it up
return form;
}
@RequestMapping(value="/editMyInfo", method = RequestMethod.GET)
public String editMyInfo(ModelMap model ) {
loadReferenceData(model);
return "contactEdit";
}
@RequestMapping(value="/editMyInfo", method = RequestMethod.POST)
public String saveMyInfo(ModelMap model, MyInfoForm form,BindingResult result ) {
validator.validate (form,result);
if (result.hasErrors()) {
model.put("commandName", "myInfoForm");
return "contactEdit";
}
//save some stuff
return "redirect:viewMyInfo";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不直接做
Why not just do
您应该在注释 @ModelAttribute 的帮助下提供参考数据,例如您的 CountryDivisions。这样做的一个很大的优点是,您不需要一遍又一遍地重复并在多种方法中提供相同的数据。
对于您的示例,我将提供如下内容:
这使您的视图可以访问名为“countryDivisions”的模型属性,该属性包含由“countryDivisionService”的服务方法提供的“CountryDivison”对象列表。
You should provide reference data like your CountryDivisions with the help of the annotation @ModelAttribute. This has the great advantage that you don't need to repeat yourself over and over and provide the same data within multiple methods.
For your example I would provide something like this:
This gives your views access to a model attribute called "countryDivisions" that holds a list of "CountryDivison"-objects provided by the service method from your "countryDivisionService".