Spring Validator - show errors using <form:errors

百般思念 提交于 2020-01-04 05:03:26

问题


I am working in a spring mvc web app where i am trying to validate an db object person using Spring's Validator and trying to show the result of validator in JSP form as form:errors path="". I have server side method in a controller as :

@RequestMapping( value="/find", method = RequestMethod.GET )
public ModelAndView search(@ModelAttribute("Person") Person p,BindingResult result){

     Person person2 = personDao.get( p.getId() );
     ModelAndView mav = new ModelAndView("templates/person");

     PersonValidator personValidator = new PersonValidator();
     personValidator.validate(person2, result);
     mav.addObject("person",person2);
     mav.addObject("errors",result.getFieldErrors());

     return mav;
}

I have JSP code as :

<form:form commandName="person" >
    <form:input path="personEmail" /> 
    <form:errors path="personEmail"  element="div" />
</form:form>

It works if I explicitly put the error message ${errors.personEmail }

But ,

<form:errors path="personEmail"  element="div" />

does not work.

Could you please suggest me what's wrong here?


回答1:


I did the following changes and it is solved now. :D

@RequestMapping( value="/find", method = RequestMethod.GET )
    public String search(@ModelAttribute("Person") Person p,BindingResult result,ModelMap model){

         Person person2 = personDao.get( p.getId() );
         PersonValidator personValidator = new PersonValidator();
         Errors errors = new BeanPropertyBindingResult(person2, "person");
         personValidator.validate(person2, errors);
         model.addAttribute("person",person2);
         model.addAttribute("errors",errors);

         return "templates/person";
 }



回答2:


please try to narrow variable names.

You have got @Model Attribute("Person") where the command is named Person than in your jsp you have person and in personValidator.validate(person, result); you have person . You should validate the same object which is preceding BindingResult => Person p or you have to create binding result for particular object explicitly like this

BindingResult errors = new BeanPropertyBindingResult(person,"person");
validate(Person person, Errors errors);


来源:https://stackoverflow.com/questions/10980750/spring-validator-show-errors-using-formerrors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!