JSR303 数据校验

前端页面进行数据校验之后,提交的数据后端还需要再进行一次数据校验

1. JSR303 数据校验

1. 给bean添加校验注解 javax.validation.constraints 

package com.zx.zxmall.product.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;
import java.util.Date;
import lombok.Data;
import org.hibernate.validator.constraints.URL;

import javax.validation.constraints.*;

/**
 * 品牌
 * 
 * @author zx
 * @email [email protected]
 * @date 2020-06-10 23:31:58
 */
@Data
@TableName("pms_brand")
public class BrandEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
	 * 品牌id
	 */
	@TableId
	private Long brandId;
	/**
	 * 品牌名
	 * @NotBlank 必须有一个非空格字符
	 */
	@NotBlank
	private String name;
	/**
	 * 品牌logo地址
	 */
	private String logo;
	/**
	 * 介绍
	 */
	private String descript;
	/**
	 * 显示状态[0-不显示;1-显示]
	 */
	private Integer showStatus;
	/**
	 * 检索首字母
	 */
	private String firstLetter;
	/**
	 * 排序
	 */
	private Integer sort;

}


2. 开启校验功能@Valid

    @RequestMapping("/save")
    //@RequiresPermissions("product:brand:save")
    public R save(@Valid @RequestBody BrandEntity brand){
        brandService.save(brand);
        return R.ok();
    }

3. 使用postman发送数据

{"name":""}

http://localhost:88/api/product/brand/save

{
    "timestamp": "2020-06-20T23:40:29.294+0000",
    "status": 400,
    "error": "Bad Request",
    "errors": [
        {
            "codes": [
                "NotBlank.brandEntity.name",
                "NotBlank.name",
                "NotBlank.java.lang.String",
                "NotBlank"
            ],
            "arguments": [
                {
                    "codes": [
                        "brandEntity.name",
                        "name"
                    ],
                    "arguments": null,
                    "defaultMessage": "name",
                    "code": "name"
                }
            ],
            "defaultMessage": "不能为空",
            "objectName": "brandEntity",
            "field": "name",
            "rejectedValue": "",
            "bindingFailure": false,
            "code": "NotBlank"
        }
    ],
    "message": "Validation failed for object='brandEntity'. Error count: 1",
    "path": "/product/brand/save"
}

默认的提示信息是按照ValidationMessages_zh_CN.properties中的配置信息进行提示

javax.validation.constraints.AssertFalse.message     = 只能为false
javax.validation.constraints.AssertTrue.message      = 只能为true
javax.validation.constraints.DecimalMax.message      = 必须小于或等于{value}
javax.validation.constraints.DecimalMin.message      = 必须大于或等于{value}
javax.validation.constraints.Digits.message          = 数字的值超出了允许范围(只允许在{integer}位整数和{fraction}位小数范围内)
javax.validation.constraints.Email.message           = 不是一个合法的电子邮件地址
javax.validation.constraints.Future.message          = 需要是一个将来的时间
javax.validation.constraints.FutureOrPresent.message = 需要是一个将来或现在的时间
javax.validation.constraints.Max.message             = 最大不能超过{value}
javax.validation.constraints.Min.message             = 最小不能小于{value}
javax.validation.constraints.Negative.message        = 必须是负数
javax.validation.constraints.NegativeOrZero.message  = 必须是负数或零
javax.validation.constraints.NotBlank.message        = 不能为空
javax.validation.constraints.NotEmpty.message        = 不能为空
javax.validation.constraints.NotNull.message         = 不能为null
javax.validation.constraints.Null.message            = 必须为null

可以定义自己的message信息进行提示

package com.zx.zxmall.product.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;
import java.util.Date;
import lombok.Data;
import org.hibernate.validator.constraints.URL;

import javax.validation.constraints.*;

/**
 * 品牌
 * 
 * @author zx
 * @email [email protected]
 * @date 2020-06-10 23:31:58
 */
@Data
@TableName("pms_brand")
public class BrandEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
	 * 品牌id
	 */
	@TableId
	private Long brandId;
	/**
	 * 品牌名
	 * @NotBlank 必须有一个非空格字符
	 */
	@NotBlank(message = "品牌名必须提交")
	private String name;
	/**
	 * 品牌logo地址
	 */
	@NotEmpty
	@URL(message = "logo必须是一个合法的url地址")
	private String logo;
	/**
	 * 介绍
	 */
	private String descript;
	/**
	 * 显示状态[0-不显示;1-显示]
	 */
	private Integer showStatus;
	/**
	 * 检索首字母
	 */
	//自定义规则 @Pattern
	@NotEmpty
	@Pattern(regexp = "/^[a-zA-Z]$/",message = "检索首字母必须是一个字母")
	private String firstLetter;
	/**
	 * 排序
	 */
	@NotNull
	@Min(value = 0,message = "排序必须大于等于0")
	private Integer sort;

}

 给校验的bean后紧跟一个BindingResult,就可以获取到校验的结果

    @RequestMapping("/save")
    //@RequiresPermissions("product:brand:save")
    public R save(@Valid @RequestBody BrandEntity brand, BindingResult result){
        if(result.hasErrors()){
            Map map=new HashMap<>();
            //1.获取校验的错误结果
            result.getFieldErrors().forEach((item)->{
                //FieldError获取到错误提示
                String message=item.getDefaultMessage();
                //获取错误的属性的名字
                String field=item.getField();
                map.put(field,message);
            });
            return R.error(400,"提交的数据不合法").put("data",map);
        }else{
            brandService.save(brand);
        }
        return R.ok();
    }

使用postman提交数据   

http://localhost:88/api/product/brand/save

提交数据 
{"name":""}
 
{
    "msg": "提交的数据不合法",
    "code": 400,
    "data": {
        "name": "品牌名必须提交",
        "logo": "不能为空",
        "sort": "不能为null",
        "firstLetter": "不能为空"
    }
}

{"name":"abc","logo":"abc"}
{
    "msg": "提交的数据不合法",
    "code": 400,
    "data": {
        "logo": "logo必须是一个合法的url地址",
        "sort": "不能为null",
        "firstLetter": "不能为空"
    }
}

注:

@NotEmpty的标注范围

@NotNull 可以标注任意类型

/**
 * The annotated element must not be {@code null} nor empty.
 * 

* Supported types are: *

    *
  • {@code CharSequence} (length of character sequence is evaluated)
  • *
  • {@code Collection} (collection size is evaluated)
  • *
  • {@code Map} (map size is evaluated)
  • *
  • Array (array length is evaluated)
  • *
* * @author Emmanuel Bernard * @author Hardy Ferentschik * * @since 2.0 */ @Documented @Constraint(validatedBy = { }) @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) @Retention(RUNTIME) @Repeatable(List.class) public @interface NotEmpty{} ------ /** * The annotated element must not be {@code null}. * Accepts any type. * * @author Emmanuel Bernard */ @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) @Retention(RUNTIME) @Repeatable(List.class) @Documented @Constraint(validatedBy = { }) public @interface NotNull {}

2. 统一异常处理

1. 编写异常处理类 使用@ControllerAdvice

使用@ExceptionHandler标注方法可以处理的异常

package com.zx.zxmall.product.exception;

import com.zx.common.exception.BizCodeEnum;
import com.zx.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
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.bind.annotation.RestControllerAdvice;

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

/**
 * 集中处理所有异常
 */
@Slf4j
//@ResponseBody
//@ControllerAdvice(basePackages = "com.zx.zxmall.product.controller")
@RestControllerAdvice(basePackages = "com.zx.zxmall.product.controller")
public class ZxMallExceptionControllerAdvice {

//   @ExceptionHandler(value = Exception.class)
//   public R handleValidException(Exception e){
//        log.error("数据校验出现异常{},异常类型{}",e.getMessage(),e.getClass());
//        return R.error();
//        //"msg": "未知异常,请联系管理员",
//        //    "code": 500
//   }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现异常{},异常类型{}", e.getMessage(), e.getClass());
        BindingResult bindingResult=e.getBindingResult();
        Map errorMap=new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError)->{
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data",errorMap);
        //return R.error(400,"数据校验出现问题").put("data",errorMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }
}
package com.zx.common.exception;

/**
 * 系统错误码
 *  * 1,错误码定义规则为5为数字
 *  * 2,前两位表示业务场景,最后三位表示错误码。
 *  *   例如:100001,10:通用    001:系统未知异常
 *  * 3,维护错误码后需要维护错误描述,将他们定义为枚举形式
 *  * 错误码列表
 *  * 10:通用
 *  *  001:参数格式校验
 *  * 11:商品
 *  * 12:订单
 *  * 13:购物车
 *  * 14:物流
 */
public enum BizCodeEnum {

    UNKNOW_EXCEPTION(10000,"系统未知异常"),
    VALID_EXCEPTION(10001,"参数格式校验失败");

    private int code;
    private String msg;

    BizCodeEnum(int code,String msg){
        this.code=code;
        this.msg=msg;
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}
{"name":"abc","logo":"abc"}

{
    "msg": "参数格式校验失败",
    "code": 10001,
    "data": {
        "logo": "logo必须是一个合法的url地址",
        "sort": "不能为null",
        "firstLetter": "不能为空"
    }
}

3. 分组校验

1. 给校验注解标注什么情况需要进行校验
 

    @NotNull(message = "修改必须指定品牌id",groups = {UpdateGroup.class})
	@Null(message = "新增不能指定id",groups = {AddGroup.class})
	@TableId
	private Long brandId;
	/**
	 * 品牌名
	 * @NotBlank 必须有一个非空格字符
	 */
	
	@NotBlank(message = "品牌名必须提交",groups = {AddGroup.class,UpdateGroup.class})
	private String name;
package com.zx.common.exception;

public class UpdateGroup {
}


------
package com.zx.common.exception;

public interface AddGroup {
}

 

2. @Validated({AddGroup.class})

    @RequestMapping("/save")
    //@RequiresPermissions("product:brand:save")
    public R save(@Validated({AddGroup.class}) @RequestBody BrandEntity brand){
        brandService.save(brand);
        return R.ok();
    }

 

{"name":"abc","logo":"abc","brandId":"3"}

{
    "msg": "参数格式校验失败",
    "code": 10001,
    "data": {
        "brandId": "新增不能指定id"
    }
}

//没有标注分组的默认不生效,让其生效就必须指定分组
{"name":"abc","logo":"abc"}
{
    "msg": "success",
    "code": 0
}

3. 默认没有指定分组的校验注解@NotBlank 在分组校验情况@Validated({UpdateGroup.class})下不生效, 只会在@Valid生效

package com.zx.zxmall.product.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;
import java.util.Date;

import com.zx.common.exception.AddGroup;
import com.zx.common.exception.UpdateGroup;
import lombok.Data;
import org.hibernate.validator.constraints.URL;

import javax.validation.constraints.*;

/**
 * 品牌
 * 
 * @author zx
 * @email [email protected]
 * @date 2020-06-10 23:31:58
 */
@Data
@TableName("pms_brand")
public class BrandEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
	 * 品牌id
	 */
	@NotNull(message = "修改必须指定品牌id",groups = {UpdateGroup.class})
	@Null(message = "新增不能指定id",groups = {AddGroup.class})
	@TableId
	private Long brandId;
	/**
	 * 品牌名
	 * @NotBlank 必须有一个非空格字符
	 */

	@NotBlank(message = "品牌名必须提交",groups = {AddGroup.class,UpdateGroup.class})
	private String name;
	/**
	 * 品牌logo地址
	 * 新增不能为空
	 */
	@NotEmpty(groups = {AddGroup.class})
	@URL(message = "logo必须是一个合法的url地址",groups = {AddGroup.class,UpdateGroup.class})
	private String logo;
	/**
	 * 介绍
	 */
	private String descript;
	/**
	 * 显示状态[0-不显示;1-显示]
	 */
	private Integer showStatus;
	/**
	 * 检索首字母
	 */
	//自定义规则 @Pattern
	@NotEmpty(groups = {AddGroup.class})
	@Pattern(regexp = "/^[a-zA-Z]$/",message = "检索首字母必须是一个字母",groups = {AddGroup.class,UpdateGroup.class})
	private String firstLetter;
	/**
	 * 排序
	 */
	@NotNull(groups = {AddGroup.class})
	@Min(value = 0,message = "排序必须大于等于0",groups = {AddGroup.class,UpdateGroup.class})
	private Integer sort;

}
    @RequestMapping("/save")
    //@RequiresPermissions("product:brand:save")
    public R save(@Validated({AddGroup.class}) @RequestBody BrandEntity brand){
        brandService.save(brand);
        return R.ok();
    }
    /**
     * 修改
     */
    @RequestMapping("/update")
   // @RequiresPermissions("product:brand:update")
    public R update(@Validated({UpdateGroup.class}) @RequestBody BrandEntity brand){
		brandService.updateById(brand);
        return R.ok();
    }

4. 自定义校验

 1.编写一个自定义的校验注解

package com.zx.common.valid;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Documented
@Constraint(validatedBy = { ListValueConstraintValidator.class})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
public @interface ListValue {

    String message() default "{com.zx.common.valid.ListValue.message}";

    Class[] groups() default { };

    Class[] payload() default { };

    int[] vals() default {};
}

添加ValidationMessages.properties 

com.zx.common.valid.ListValue.message=必须提交指定的值

 2.编写一个自定义的校验器

package com.zx.common.valid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

public class ListValueConstraintValidator implements ConstraintValidator {

    Set set=new HashSet<>();
    //初始化方法
    @Override
    public void initialize(ListValue constraintAnnotation) {
        int[] vals=constraintAnnotation.vals();
        for(int val:vals){
            set.add(val);
        }
    }

    //判断是否校验成功

    /**
     *
     * @param value 需要校验的值
     * @param constraintValidatorContext
     * @return
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
        return set.contains(value);
    }
}

 3.关联自定义的校验器和自定义的校验注解

    @ListValue(vals={0,1},groups = {AddGroup.class})
	private Integer showStatus;
http://localhost:88/api/product/brand/save

{"name":"abc","logo":"abc","showStatus":3}

{
    "msg": "参数格式校验失败",
    "code": 10001,
    "data": {
        "logo": "logo必须是一个合法的url地址",
        "showStatus": "必须提交指定的值",
        "sort": "不能为null",
        "firstLetter": "不能为空"
    }
}

 

你可能感兴趣的:(SpringCloud)