@NotBlank与@Validated在参数校验时的使用

Posted SSimeng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了@NotBlank与@Validated在参数校验时的使用相关的知识,希望对你有一定的参考价值。

1. 在实体类(Student.class)对应的字段加上注解,message为需要提示的信息

package com.example.demo.entity;

import lombok.Data;
import lombok.ToString;

import javax.validation.constraints.NotBlank;
@Data
@ToString
public class Student 
    private int id;
    @NotBlank(message = "学生姓名不能为空!")
    private String name;
    @NotBlank(message = "学生地址不能为空!")
    private String address;

2. 在Controller层加入@Validated,BindingResult则是校验的结果

package com.example.demo.controller;

import com.example.demo.entity.Student;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
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 java.util.ArrayList;
import java.util.List;

@RestController
public class TestController 
    @PostMapping(path = "/addStudent")
    public List<String> addStudent(@Validated @RequestBody Student student, BindingResult result)
        List<String> errorList = new ArrayList<>();
        if(result.hasErrors())
            //遍历错误集合
            for (ObjectError error :result.getAllErrors()
                    ) 
                errorList.add(error.getDefaultMessage());
            
        
        return errorList;
    

 3.结果(将校验的结果返回了)

以上是关于@NotBlank与@Validated在参数校验时的使用的主要内容,如果未能解决你的问题,请参考以下文章

@NotBlank与@Validated在参数校验时的使用

Java中的参数校验

Java中的参数校验

@Validated 和 @Valid 联合使用,完成service层参数校验

Spring boot @Validated注解以及配合@Valid的使用

@Validated注解无效,以及嵌套对象属性的@NotBlank无效问题