基于spring validation多层对象校验

1、第一层对象定义

package com.ybw.validation.demo.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.validation.Valid;
import java.io.Serializable;

/**
 * 请求参数
 *
 * @author geoffrey
 * @version V1.0
 * @className ReqIn
 * @date 2022/2/8
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ReqIn implements Serializable {

    private static final long serialVersionUID = 25549320423002325L;
    /**
     * 请求头信息
     */
    private String head;
    /**
     * 请求主体信息
     */
    @Valid
    private T data;

}

2、第二层对象

package com.ybw.validation.demo.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;

/**
 * @author geoffrey
 * @version V1.0
 * @className User
 * @date 2022/2/8
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {

	private static final long serialVersionUID = 6747944028911495569L;
	private Long id;
	@NotBlank
	private String name;
	@NotNull
	private Integer age;
}

3、Controller层校验使用

package com.ybw.validation.demo.controller;

import com.alibaba.fastjson.JSON;
import com.ybw.validation.demo.vo.ReqIn;
import com.ybw.validation.demo.vo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;


/**
 * @author geoffrey
 * @version V1.0
 * @className UserController
 * @date 2022/2/8
 **/
@RestController
@Slf4j
public class UserController {

    /**
     * 校验
     *
     * @param reqIn
     * @methodName: valid
     * @return: org.springframework.http.HttpStatus
     * @author: geoffrey
     * @date: 2022/2/8
     **/
    @PostMapping("/valid")
    public HttpStatus valid(@Valid @RequestBody ReqIn reqIn) {
        log.info("reqIn:{}", JSON.toJSONString(reqIn));
        return HttpStatus.OK;
    }
}

4、postman校验

4.1 正常情况

请求参数

{
    "data": {
        "age": 12,
        "id": 1,
        "name": "张三2"
    },
    "head": "header"
}

正常返回

基于spring validation多层对象校验_第1张图片

 4.2 校验失败

请求参数

{
    "data": {
        "age": 12,
        "id": 1,
        "name": "" //空字符串
    },
    "head": "header"
}

请求失败

基于spring validation多层对象校验_第2张图片

 

你可能感兴趣的:(spring,spring)