@valid in Spring REST

2019-09-12 04:03发布

问题:

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>

...


标签: spring rest