SpringBoot-数据验证@Validated

在springboot验证中,通常我们对前端传来的数据要进行验证,因此我们可以使用@Validated进行验证,抛出的异常方便我们判断和管理

首先我们进行@Validated验证,如果需要验证邮箱等判断,需要在maven中添加依赖

maven

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

参数解析

202202081554260

使用方法

首先我们创建一个实体类

package com.example.studentspringbootmybatisplus.entity;

import lombok.Data;

import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Email;

@Component   // 将实体类注入到bean中
@Data   // lombok
@Validated
public class Student {
    private String age;
    private String name;
    @Email    // @Email代表此字段必须要email格式
    private String email;
}

接口编写

为了演示,直接将功能编写在Controller内运行,对入参的接口加上@Validated即可对入参对象进行数字验证

package com.example.studentspringbootmybatisplus.controller;

import com.example.studentspringbootmybatisplus.entity.Student;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/demo")
public class StudentController {

    @RequestMapping("/student")    // 对Student类进行数字验证,在入参student的时候,会对里面入参的值进行数字验证
    public void getStudent(@Validated Student student){
        System.out.println(student);
    }
}

传值测试

为了方便,我这边直接使用Postman接口工具进行调用接口传值测试

202202081554260

传值错误-idea控制台输出

Field error in object 'student' on field 'email': rejected value [123]; codes [Email.student.email,Email.email,Email.java.lang.String,Email]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [student.email,email]; arguments []; default message [email],[Ljavax.validation.constraints.Pattern$Flag;@3bd56c2c,.*]; default message [不是一个合法的电子邮件地址]]

传值正确-idea控制台输出

202112141500091

Student(age=12, name=小王, email=123@outlook.com)
posted @ 2021-12-21 19:58  HeiDaotu  阅读(973)  评论(0编辑  收藏  举报