Hibernate参数校验扩展

Hibernate参数校验

一、快速入门
1. 校验bean
package com.gblfy.vo;

import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.Email;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;

/**
 * 校验扩展
 *
 * @author gblfy
 * @date 2022/06/06
 */
public class ValBean {
    
    
    /**
     * Bean Validation 中内置的 constraint
     *
     * @Null 被注释的元素必须为 null
     * @NotNull 被注释的元素必须不为 null
     * @AssertTrue 被注释的元素必须为 true
     * @AssertFalse 被注释的元素必须为 false
     * @Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
     * @Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
     * @DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
     * @DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
     * @Size(max=, min=) 被注释的元素的大小必须在指定的范围内
     * @Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
     * @Past 被注释的元素必须是一个过去的日期
     * @Future 被注释的元素必须是一个将来的日期
     * @Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式
     * Hibernate Validator 附加的 constraint
     * @NotBlank(message =) 验证字符串非null,且长度必须大于0
     * @Email 被注释的元素必须是电子邮箱地址
     * @Length(min=,max=) 被注释的字符串的大小必须在指定的范围内
     * @NotEmpty 被注释的字符串的必须非空
     * @Range(min=,max=,message=) 被注释的元素必须在合适的范围内
     */
    private Long id;
    @Max(value = 20, message = "{val.age.message}")
    private Integer age;
    @NotBlank(message = "{username.not.null}")
    @Length(max = 6, min = 3, message = "{username.length}")
    private String username;
    @NotBlank(message = "{pwd.not.null}")
    @Pattern(regexp = "/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$/", message = "密码必须是6~10位数字和字母的组合")
    private String password;
    @Pattern(regexp = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$", message = "手机号格式不正确")
    private String phone;
    @Email(message = "{email.format.error}")
    private String email;
}

2. controller
package com.gblfy.controller;

import com.gblfy.grace.result.GraceJSONResult;
import com.gblfy.vo.ValBean;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 校验控制层
 *
 * @Author gblfy
 * @Date 2022-06-06 22:13
 **/
@RestController
@RequestMapping(value = "/val")
public class ValidateController {
    
    
    @RequestMapping(value = "/val", method = RequestMethod.POST)
    @ResponseBody
    public GraceJSONResult val(@Valid @RequestBody ValBean bean, BindingResult result) throws Exception {
    
    
        if (result.hasErrors()) {
    
    
            //如果没有通过,跳转提示
            Map<String, String> map = getErrors(result);
            return GraceJSONResult.errorMap(map);
        } else {
    
    
            //继续业务逻辑
        }
        return GraceJSONResult.ok();
    }

    private Map<String, String> getErrors(BindingResult result) {
    
    
        Map<String, String> map = new HashMap<String, String>();
        List<FieldError> list = result.getFieldErrors();
        for (FieldError error : list) {
    
    
            System.out.println("error.getField():" + error.getField());
            System.out.println("error.getDefaultMessage():" + error.getDefaultMessage());
            map.put(error.getField(), error.getDefaultMessage());
        }
        return map;
    }
}

二、企业实战
2.1. 校验bean

同上

2.2. controller
package com.gblfy.controller;

import com.gblfy.grace.result.GraceJSONResult;
import com.gblfy.vo.ValBean;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 校验控制层
 *
 * @Author gblfy
 * @Date 2022-06-06 22:13
 **/
@RestController
@RequestMapping(value = "/val")
public class ValidateController {
    
    

    @RequestMapping(value = "/val", method = RequestMethod.POST)
    @ResponseBody
    public GraceJSONResult val(@Valid @RequestBody ValBean bean) {
    
    

        //TODO 业务处理
        return GraceJSONResult.ok();
    }

}

2.3. 全局异常拦截
package com.gblfy.exceptions;

import com.gblfy.grace.result.GraceJSONResult;
import com.gblfy.grace.result.ResponseStatusEnum;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统一异常拦截处理
 * 可以针对异常的类型进行捕获,然后返回json信息到前端
 */
@ControllerAdvice
public class GraceExceptionHandler {
    
    

    @ExceptionHandler(MyCustomException.class)
    @ResponseBody
    public GraceJSONResult returnMyException(MyCustomException e) {
    
    
        e.printStackTrace();
        return GraceJSONResult.exception(e.getResponseStatusEnum());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public GraceJSONResult returnMethodArgumentNotValid(MethodArgumentNotValidException e) {
    
    
        BindingResult result = e.getBindingResult();
        Map<String, String> map = getErrors(result);
        return GraceJSONResult.errorMap(map);
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseBody
    public GraceJSONResult returnMaxUploadSize(MaxUploadSizeExceededException e) {
    
    
        return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_MAX_SIZE_2MB_ERROR);
    }

    public Map<String, String> getErrors(BindingResult result) {
    
    
        Map<String, String> map = new HashMap<>();
        List<FieldError> errorList = result.getFieldErrors();
        for (FieldError ff : errorList) {
    
    
            // 错误所对应的属性字段名
            String field = ff.getField();
            // 错误的信息
            String msg = ff.getDefaultMessage();
            map.put(field, msg);
        }
        return map;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40816738/article/details/125155374
今日推荐