JSR303数据校验学习笔记

JSR-303 数据校验

常用注解

Annotation应用位置作用
@NotNullfield/property检查该值不为null
@NotBlankfield/property检查该字符串不为null,并且不是空字符串. 本约束和下面的@NotEmpty的不同之处在于,本约束只能被用在字符串类型上,并且会忽略字符串尾部的空白字符
@NotEmpty字段或属性. 支持的类型包括String, Collection, Map 和数组检查该值不为null同时也不为空
@URL字段或属性, 要求其类型为String判断该值是否是一个有效的URL, 如果给出了约束中的protocol, host 或 port 参数的话,那个被校验的值需要和其匹配
@Valid字段或属性. 支持所有的非原始类型递归的对关联对象进行校验, 如果关联对象是个集合或者数组, 那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验

更多查看注解使用教程

使用方法

1.实体类属性添加注解

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

public class Student implements Serializable {

	@NotNull
    private int age;
    @NotBlank
    private String name;
    
}

2.controller

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
public class StudentController {


    /**
     * 开启数据校验  @Valid
     * @param student
     * @return
     */
    @RequestMapping(value = "/test",method = RequestMethod.POST)
    public R test(@Valid @RequestBody Student student){
        System.out.println(student.toString());
        return new R(0,"SUCCESS",null);
    }


}

3.效果展示

name不为空请求成功

在这里插入图片描述

name为空返回异常信息
在这里插入图片描述

4.工具类

/**
 * 封装返回结果
 */
public class R<T> {

    private int code;
    private String msg;
    private T data;
    // 构造方法省略
    // getter setter 省略
}


/**
 * 封装全局异常结果
 */
@RestControllerAdvice(basePackages = "需要扫描的包")
public class ExceptionControllerAdvice {


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();

        Map<String,String> map = new HashMap<>();
        result.getFieldErrors().forEach((item) -> {
            // 错误信息 item.getDefaultMessage()
            // 获取错误的属性名 item.getField()
            map.put(item.getField(),item.getDefaultMessage());
        });
        return new R(500,"数据校验错误",map);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值