【JAVA】Java中使用 hibernate-validator 校验参数

Java中使用 hibernate-validator 校验参数
hibernate-validator官网

平时在开发过程中我们使用if判断来验证参数是否正确,如果验证的参数比较多就要写一堆if判断代码,代码看起来非常多,如果使用hibernate-validator来校验参数就非常方便也不用写大量的if判断

1.引入pom依赖
版本号可以自己改

<!--    参数校验    -->
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.2.0.Final</version>
</dependency>

2.验证参数

1. json格式验证

  1. 创建一个Java对象
package com.xhs.annotation.request;

import lombok.Data;

import javax.validation.constraints.NotEmpty;

/**
 * @desc: 用户入参
 * @author: xhs
 * @date: 2021/5/24 14:09
 * @version: JDK 1.8
 */
@Data
public class UserRequest {

    /**
     * 用户名
     */
    @NotEmpty(message = "用户名不能为空")
    private String userNm;

    /**
     * 密码
     */
    @NotEmpty(message = "密码不能为空")
    private String pwd;

}
  1. 创建controller
    注意 @Valid注解就是验证参数的
package com.xhs.annotation.controller;

import com.xhs.annotation.request.UserRequest;
import lombok.extern.slf4j.Slf4j;
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.HashMap;

/**
 * @desc:
 * @author: xhs
 * @date: 2021/5/24 14:18
 * @version: JDK 1.8
 */
@Slf4j
@RestController
public class UserController {

    @PostMapping("/user")
    public HashMap<String, Object> user(@RequestBody @Valid UserRequest userRequest) {
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("code", 200);
        map.put("msg", "处理成功");
        map.put("data", userRequest);
        return map;
    }
}
  1. 使用SpringMVC中的@ControllerAdvice注解全局异常处理来处理参数
package com.xhs.annotation.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Set;

/**
 * @desc: 全局异常处理
 * @author: xhs
 * @date: 2021/5/24 14:23
 * @version: JDK 1.8
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler
    public HashMap<String, Object> exceptionHandler(Exception e) {
        log.info(">>>>>>>>>>>>>>>>>>全局异常:{}<<<<<<<<<<<<<<<<<<<<<<<<<<<<<", e.getMessage());
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("code", 500);
        map.put("msg", "系统处理失败,请联系管理员");
        return map;
    }

    /**
     * JSON格式参数校验失败
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public HashMap<String, Object> validateHandlerJson(MethodArgumentNotValidException e) {
        log.info(">>>>>>>>>>>>>>>>>>JSON格式参数校验失败:{}<<<<<<<<<<<<<<<<<<<<<<<<<<<<<", e.getMessage());
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("code", 500);
        map.put("msg", "参数校验失败");
        map.put("msg", e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return map;
    }

    /**
     * 单个参数校验失败
     *
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public HashMap<String, Object> validateHandler(ConstraintViolationException e) {
        log.info(">>>>>>>>>>>>>>>>>>单个参数校验失败:{}<<<<<<<<<<<<<<<<<<<<<<<<<<<<<", e.getMessage());
        StringBuilder errorInfo = new StringBuilder();
        String errorMessage;
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        for (ConstraintViolation<?> item : violations) {
            errorInfo.append(item.getMessage()).append(",");
        }
        errorMessage = errorInfo.toString().substring(0, errorInfo.toString().length() - 1);
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("code", 500);
        map.put("msg", errorMessage);
        return map;
    }
}

  1. 处理结果
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

2. 单个参数验证
单个参数验证在controller上加上@Validated

package com.xhs.annotation.controller;

import com.xhs.annotation.request.UserRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
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 javax.validation.constraints.NotEmpty;
import java.util.HashMap;

/**
 1. @desc:
 2. @author: xhs
 3. @date: 2021/5/24 14:18
 4. @version: JDK 1.8
 */
@Slf4j
@Validated
@RestController
public class UserController {

    @PostMapping("/user")
    public HashMap<String, Object> user(@RequestBody @Valid UserRequest userRequest) {
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("code", 200);
        map.put("msg", "处理成功");
        map.put("data", userRequest);
        return map;
    }

    @GetMapping("/getUser")
    public HashMap<String, Object> getUser(@NotEmpty(message = "用户名不能为空") String name,
                                           @NotEmpty(message = "密码不能为空") String pwd) {
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("code", 200);
        map.put("msg", "处理成功");
        map.put("data", name);
        return map;
    }
}
  1. 处理结果:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3.常用注解

javax.validation.constraints 的注解和 org.hibernate.validator.constraints 的注解可以混用

  1. javax.validation.constraints 的注解
注解使用
@NotBlank只用来校验字符串不能为null,空格也是被允许的 。校验字符串推荐使用@NotEmpty
@NotNull被注释的元素,值不能为null,但可以为"空",用于基本数据类型的非空校验上,而且被其标注的字段可以使用 @size、@Max、@Min 等对字段数值进行大小的控制
@NotEmpty用来校验字符串、集合、map、数组不能为null或空(字符串传入空格也不可以)(集合需至少包含一个元素)
@Pattern(regexp = “”, message = “”)正则表达式匹配
@Size(min =, max =)指定的字符串、集合、map、数组长度必须在指定的max和min内允许元素为null,字符串允许为空格
@Min(value = long以内的值, message = “”)校验数字(包括integer short long int 等)的最小值,不支持小数即double和float允许元素为null
@Max(value = long以内的值, message = “”)校验数字(包括integer short long int 等)的最小值,不支持小数即double和float允许元素为null
@DecimalMin(value = 可以是小数, message = “”)被注释的元素,值必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value = 可以是小数, message = “”)被注释的元素,值必须是一个数字,其值必须小于等于指定的最大值
@Digits(integer =, fraction =)被注释的元素必须是一个数字,其值必须在可接受的范围内
@AssertTrue(message = “”)被注释的元素,值必须为true
@AssertFalse被注释的元素,值必须为false
@Email(regexp = “”, message = “”)被注释的元素必须是电子邮件地址
  1. org.hibernate.validator.constraints 的注解
注解使用
@Range(min =, max =, message = “”)被注释的元素必须在合适的范围内
@Length(min =, max =, message = “”)被注释的字符串的大小必须在指定的范围内
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值