form:errors doesn't render on jsp

情到浓时终转凉″ 提交于 2019-12-12 01:27:54

问题


I have following controller:

@RequestMapping(value = "/member/createCompany/addParams", method = RequestMethod.POST)
    public String setCompanyParams(
            @ModelAttribute MyDto myDto,
            @RequestParam(value = "g-recaptcha-response") String recapchaResponse,
            HttpSession session, Principal principal, Model model) throws Exception {

        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<MyDto>> violations;        
        if(condition1){
               violations = validator.validate(myDto, ValidationGroup1.class);
        } else {
              violations = validator.validate(myDto);
        }
        if (violations.size() > 0) {
            return "member/createCompany/addParams";
        }
        ...
}

MyDto class:

class MyDto {
    @NotEmpty
    String companyName;    

    @NotEmpty(groups = ValidationGroup1.class)
    String generatedPassword;
}

and following jsp:

   <form:form commandName="myDto" id="addParams" action="/member/createCompany/addParams" method="POST">
                        <form:errors cssClass="error"  path="companyName"/><br/>
                        <form:input type="text" id="companyName" path="companyName" name="companyName" maxlength="255" value="${campaign.campaignName}"/><br/>

                        <form:errors cssClass="error"  path="generatedPassword"/><br/>
                        <form:input path="generatedPassword" type="text" id="generatedPassword" name="generatedPassword" value="${generatedPassword}" />
                         ... 
   </form:form>     

When I submit form I see that

violations.size() > 0 is true

but when I see rendered page I dont see error messages.
What the problem?


回答1:


As I said in my answer to you previous question, that's not the way Spring MVC validations work.

Spring MVC comes with a lot of magic ... provided you follow its rules. For the <form:errors .../> tags to work, you must have an Errors object in the response tied to the ModelAttribute object. It happens automagically if you put one BindingResult as a method parameter immediately after the model attribute (see refed answer)

Unfortunately, when you do that, Spring will validate every field, which is not what you want, without any simple way to ignore errors on some fields. So you could :

  • put no automatic validator through an @InitBinder annotated method
  • and either
    • explicitely reject fields by doing a manual validation (or depending of your violation) - a bit manual, but robust method
    • use a SpringValidatorAdapter around your JSR-303 validator as it can use validation groups as validation hints through its SmartValidator interface and explicitely calls its method void validate(Object target, Errors errors, Object... validationHints) in your controller.

Anyway, I strongly advice you not to create a validator for each request, but create it as a bean and inject it in your controller.



来源:https://stackoverflow.com/questions/29616089/formerrors-doesnt-render-on-jsp

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