SpringMVC自定义注解校验前端参数

关于分组校验参考:https://blog.csdn.net/weixin_42465125/article/details/100696587

pom.xml配置:

        <!-- swagger start -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.9.2</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>2.0.1.Final</version>
		</dependency>

        <dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.16.22</version>
			<scope>provided</scope>
		</dependency>
package cn.cuit.test1;
/**
 * @ClassName:  Add   
 * @Description:新加验证组
 *     
 * @Copyright: 2018
 */
public interface Add {

}
package cn.cuit.test1;

public interface Update {

}

VO实体:

package cn.cuit.test1;


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

import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;


@ApiModel(value = "CcCfgAlarmInfo对象", description = "报警配置信息表")
@CheckCfgHighLow(groups = {Add.class, Update.class})
@Data
public class CcCfgAlarmInfoDto implements Serializable
{

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "ID主键")
    private Long id;

    @ApiModelProperty(value = "高点位")
    @Min(value = 0, message = " should be legal number", groups = {Add.class, Update.class})
    private Long highspot;

    @ApiModelProperty(value = "中间线一侧连续点数")
    @Min(value = 0, message = " should be legal number", groups = {Add.class, Update.class})
    private Long medianlineOneSide;

    @ApiModelProperty(value = "中位点线")
    @Min(value = 0, message = " should be legal number", groups = {Add.class, Update.class})
    private Long medianspot;

    @ApiModelProperty(value = "低点位")
    @Min(value = 0, message = " should be legal number", groups = {Add.class, Update.class})
    private Long lowspot;

    @ApiModelProperty(value = "报警上升连续点数量")
    @Min(value = 0, message = " should be legal number", groups = {Add.class, Update.class})
    private Long continuousUp;

    @ApiModelProperty(value = "报警下降连续点数量")
    @Min(value = 0, message = " should be legal number", groups = {Add.class, Update.class})
    private Long continuousDown;

    @ApiModelProperty(value = "产线")
    @NotEmpty(message = " parameter cannot be null", groups = {Add.class, Update.class})
    private String lineName;

    @ApiModelProperty(value = "状态")
    private String status;

    @ApiModelProperty(value = "创建人")
    private String createBy;

    @ApiModelProperty(value = "修改人")
    private String updateBy;

    @ApiModelProperty(value = "创建时间")
    private Date createTime;

    @ApiModelProperty(value = "修改时间")
    private Date updateTime;

    @ApiModelProperty(value = "备注")
    private String remarks;

    @ApiModelProperty(value = "是否移除")
    private String delFlag;

    @ApiModelProperty(value = "版本号")
    private Long version;    
}

自定义校验注解:

package cn.cuit.test1;


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.RetentionPolicy.RUNTIME;


@Target({FIELD, TYPE})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = CheckTwoNumValidator.class)
public @interface CheckCfgHighLow {

    boolean required() default true;

    String message() default "Config Error: The high spot should be greater than median spot and low spot, The median spot should be greater than low spot";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

定义校验器:

package cn.cuit.test1;


import java.util.Objects;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;


/**
 * 
  * @ClassName: CheckTwoNumValidator
  * @Description: 检查高位、中位、低位数字的合法性
  * @author CUITLLB
  * @date Oct 15, 2019 8:25:25 AM
  * @Copyright: Copyright (c) 2018 
 */
public class CheckTwoNumValidator implements ConstraintValidator<CheckCfgHighLow, CcCfgAlarmInfoDto>
{

    private boolean required = false;

    @Override
    public void initialize(CheckCfgHighLow constraintAnnotation)
    {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(CcCfgAlarmInfoDto cfg, ConstraintValidatorContext constraintValidatorContext)
    {
        if (required)
        {
            if (cfg.getHighspot() <= cfg.getMedianspot())
            {
                constraintValidatorContext.disableDefaultConstraintViolation();
                constraintValidatorContext.buildConstraintViolationWithTemplate(
                    String.format("highSpot=%s, medianSpot=%s The high spot should be greater than median spot", cfg.getHighspot(), cfg.getMedianspot())).addConstraintViolation();
                return false;
            }
            if (cfg.getHighspot() <= cfg.getLowspot())
            {
                constraintValidatorContext.disableDefaultConstraintViolation();
                constraintValidatorContext.buildConstraintViolationWithTemplate(
                    String.format("highSpot=%s, lowSpot=%s The high spot should be greater than low spot", cfg.getHighspot(), cfg.getLowspot())).addConstraintViolation();
                return false;
            }
            if (cfg.getMedianspot() <= cfg.getLowspot())
            {
                constraintValidatorContext.disableDefaultConstraintViolation();
                constraintValidatorContext.buildConstraintViolationWithTemplate(
                    String.format("medianSpot=%s, lowSpot=%s The median spot should be greater than low spot", cfg.getMedianspot(), cfg.getLowspot())).addConstraintViolation();
                return false;
            }

            return true;
        }
        else
        {
            if (Objects.isNull(cfg))
            {
                return false;
            }
            else
            {
                if (cfg.getHighspot() <= cfg.getMedianspot())
                {
                    constraintValidatorContext.disableDefaultConstraintViolation();
                    constraintValidatorContext.buildConstraintViolationWithTemplate(String.format("highSpot=%s, medianSpot=%s The high spot should be greater than median spot",
                        cfg.getHighspot(), cfg.getMedianspot())).addConstraintViolation();
                    return false;
                }
                if (cfg.getHighspot() <= cfg.getLowspot())
                {
                    constraintValidatorContext.disableDefaultConstraintViolation();
                    constraintValidatorContext.buildConstraintViolationWithTemplate(
                        String.format("highSpot=%s, lowSpot=%s The high spot should be greater than low spot", cfg.getHighspot(), cfg.getLowspot())).addConstraintViolation();
                    return false;
                }
                if (cfg.getMedianspot() <= cfg.getLowspot())
                {
                    constraintValidatorContext.disableDefaultConstraintViolation();
                    constraintValidatorContext.buildConstraintViolationWithTemplate(
                        String.format("medianSpot=%s, lowSpot=%s The median spot should be greater than low spot", cfg.getMedianspot(), cfg.getLowspot())).addConstraintViolation();
                    return false;
                }

                return true;
            }
        }
    }
}

注意事项:注意自定义注解的位置,因为是对类里面的多个不同字段进行计算校验,注解应该加在类上,而不是单独的某个字段上,如果是单独校验某一个字段则相比这个简单一些

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值