【问题标题】:@valid in Spring REST@valid 在 Spring REST 中
【发布时间】:2016-02-11 17:13:50
【问题描述】:

我正在尝试在 Spring 3.x 中开发 REST API。出于验证的目的,@Valid 似乎符合我的要求。如何从has.error() 中检索错误?有没有办法自定义错误信息?

【问题讨论】:

    标签: spring 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>
    
    ...
    

    【讨论】:

      猜你喜欢
      • 2013-05-15
      • 2018-06-23
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 2020-10-04
      • 1970-01-01
      相关资源
      最近更新 更多