2016-02-11 37 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> 

...