【问题标题】:Spring mvc validation restSpring mvc验证休息
【发布时间】:2016-12-30 12:01:25
【问题描述】:

嗨,我在这里有这个方法,现在我想对此进行验证,如何做到这一点任何人都可以解释我是 spring 的新手。我正在使用 json 将值绑定到使用 @Requestbody 的 Employee 并且我想验证所有字段和 json 数组,如果任何字段有错误。

var json = {"employeeid" : empID,"employeename" : empName,"joiningdate":joinDate,"emailid":emailid,"experience":experience};  


 {@RequestMapping(value = "/CreateEmployee.web",method = RequestMethod.POST)
 public String CreateUserThroughAJAX(@RequestBody String json)throws IOException}

【问题讨论】:

    标签: spring validation model-view-controller


    【解决方案1】:

    你应该这样做:

    class Employee {
    @NotNull
    private Integer employeeid;
    @NotNull
    @Length(min=3, max=50)//not sure that it is correct annotation
    private String employeeid;
    ... etc
    }
    

    和控制器方法:

    @RequestMapping(value = "/CreateEmployee.web",method = RequestMethod.POST)
     public String CreateUserThroughAJAX(@RequestBody Employee employe)throws IOException
    

    Spring 将解析您的 JSON 并创建有效实体,或者将“错误请求”作为响应(400 HTTP 状态)发送到您的客户端。

    【讨论】:

      【解决方案2】:

      首先使用验证约束定义您的 POJO 支持 bean(更多 here),例如:

      public class Employee {
      
          @NotNull
          private String name;
      
          // rest of fields + getters & setters
      
      }
      

      然后更改控制器方法签名如下:

      • 将参数类型从String更改为Employee
      • 为自动验证检查提供@Valid注解

      public String CreateUserThroughAJAX(@Valid @RequestBody Employee obj)
      

      【讨论】:

      • 但是如何将所有错误与字段名称一起添加并发送 json 作为响应
      • spring 本身(在失败的情况下)处理异常并发送带有给定异常的 json 响应,如果您想自定义错误响应它的另一个问题.. 检查例如spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
      猜你喜欢
      • 2019-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-17
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2022-01-20
      相关资源
      最近更新 更多