spring接口list校验

1、model定义

import lombok.Data;

import javax.validation.constraints.NotNull;

/**
 * @ClassName User
 * @Description:
 * @Author ybwei
 * @Date 2020/8/18
 * @Version V1.0
 **/
@Data
public class User {
    @NotNull(message = "id不为空")
    private Long id;
    @NotNull(message = "name不为空")
    private String name;
}

2、接口定义

使用@Validated+@Valid

import com.alibaba.fastjson.JSON;
import com.spring.pro.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
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;
import java.util.List;

/**
 * @ClassName: ValidateController
 * @Description:
 * @author weiyb
 * @date 2017年12月24日 上午10:26:29
 * 
 */
@RestController
@Validated
@Slf4j
public class ValidateController {

	/**
	 * @Description:
	 * @Param: [user]
	 * @Return: java.lang.String
	 * @Author: ybwei
	 * @Date: 2020/8/18
	 **/
	@PostMapping("/test")
	public String test(@Valid @RequestBody List user){
		log.info("user:{}", JSON.toJSONString(user));
		return "OK";
	}
}

3、请求参数

[{
	"id": 0,
	"name": "zhangsan0"
}, {
	"id": 1,
	"name": "zhangsan1"
}, {
	"id": 2,
	"name": "zhangsan2"
}, {
	"id": 3,
	"name": "zhangsan3"
}, {
	"name": "zhangsan4"
}]

返回结果

{
    "timestamp": "2020-08-18T06:11:40.976+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "test.user[4].id: id不为空",
    "path": "/test"
}

 

你可能感兴趣的:(spring)