在Spring REST中@valid

时间:2016-02-11 17:13:50

标签: spring rest

我试图在Spring 3.x中开发REST API。为了验证,@ Valid似乎符合我的要求。如何从has.error()中检索错误?有没有办法定制错误消息?

1 个答案:

答案 0 :(得分: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>

...