开发者

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

开发者 https://www.devze.com 2023-01-16 16:58 出处:网络
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

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
    privat开发者_如何学Goe 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. 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".


Why not just do

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

精彩评论

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