I'm trying to develop a REST API in Spring 3.x. For the purpose of validation, @Valid seems to fit my requirement. How to retrieve the errors from the has.error()
? Is there a way for customized error message?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
In order to display the error messages, you can use <form:errors>
tag on your JSP page.
See the complete example bellow.
1) Enable Validation on the Controller
@RequestMapping(value = "/addCollaborator", method = RequestMethod.POST)
public String submitCollaboratorForm(@ModelAttribute("newCollaborator") @Valid Collaborator newCollaborator, BindingResult result) throws Exception {
if(result.hasErrors()) {
return "collaboratorform";
}
collaboratorService.addCollaborator(newCollaborator);
return "redirect:/listCollaborators";
}
2) Define constraints in your domain object and customize your error messages.
public class Collaborator {
private long id;
@Pattern(regexp="91[0-9]{7}", message="Invalid phonenumber. It must start with 91 and it must have 9 digits.")
private String phoneNumber;
public Collaborator(){
}
//...
}
3) On JSP page: collaboratorform.jsp
...
<div class="container">
<h3>Add Collaborator</h3>
<form:form modelAttribute="newCollaborator" class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label" for="phoneNumber">PhoneNumber:</label>
<div class="col-sm-10">
<form:input type="text" class="form-control" id="phoneNumber" path="phoneNumber" placeholder="91 XXX XXXX" />
<!-- render the error messages that are associated with the phoneNumber field. -->
<form:errors path="phoneNumber" cssClass="text-danger"/>
</div>
</div>
<button class="btn btn-success" type="submit" value ="addCollaborator">
<span class="glyphicon glyphicon-save"></span> Add
</button>
</form:form>
</div>
...