2016-02-11 38 views
0

我试图在Spring 3.x中开发一个REST API。为了进行验证,@Valid似乎符合我的要求。如何从has.error()检索错误?有没有自定义错误信息的方法?@REST REST中无效

回答

1

为了显示错误消息,您可以在JSP页面上使用<form:errors>标记。 请参阅下面的完整示例。

1)在控制器

@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)定义的约束网域中的对象和自定义错误消息启用验证。

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)在JSP页面: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> 

...