问题
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 itsSmartValidator
interface and explicitely calls its methodvoid validate(Object target, Errors errors, Object... validationHints)
in your controller.
- explicitely reject fields by doing a manual validation (or depending of your
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