简体   繁体   English

当基于spring3注释的控制器中的表单验证失败时,参考数据将丢失

[英]reference data is lost when form fails validation in spring3 annotation based controller

I'm doing the spring 3 annotation based controller thing. 我正在做基于Spring 3注释的控制器。 Problem is, when it fails validation, the reference data is lost, namely the countryDivisions stuff. 问题是,当验证失败时,参考数据会丢失,即countryDivisions的东西。 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";
    }

}

You should provide reference data like your CountryDivisions with the help of the annotation @ModelAttribute. 您应该在注释@ModelAttribute的帮助下提供类似CountryDivisions的参考数据。 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: 对于你的例子,我会提供这样的东西:

@ModelAttribute("countryDivisions")
public List<CountryDivision> populateCountryDivisions() {
    return countryDivisionService.getCountryDivisionOrderedByCode();
}

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". 这使您的视图可以访问名为“countryDivisions”的模型属性,该属性包含由“countryDivisionService”提供的服务方法提供的“CountryDivison”对象列表。

Why not just do 为什么不这样做呢

    if (result.hasErrors()) {
        model.put("commandName", "myInfoForm");
        loadReferenceData(model);
        return "contactEdit";
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM