4.16
花费时间 1小时
代码量 150
博客量 1篇
学习知识点 参数检验
- 用到validation自定义校验
package com.di.bigevent.pojo;
import com.di.bigevent.anno.State;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import lombok.Data;
import org.hibernate.validator.constraints.URL;
import java.time.LocalDateTime;
@Data
public class Article {
private Integer id;//主键ID
@NotEmpty
@Pattern(regexp = "^\\S{1,10}$")
private String title;//文章标题
@NotEmpty
private String content;//文章内容
@NotEmpty
@URL
private String coverImg;//封面图像
@State
private String state;//发布状态 已发布|草稿
@NotNull
private Integer categoryId;//文章分类id
private Integer createUser;//创建人ID
private LocalDateTime createTime;//创建时间
private LocalDateTime updateTime;//更新时间
}
//注解类
package com.di.bigevent.anno;
import com.di.bigevent.validation.StateValidation;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.*;
@Documented//元注解
@Target({ElementType.FIELD})//元注解,filed在属性中能够使用
@Retention(RetentionPolicy.RUNTIME)//元注解
@Constraint(
validatedBy = {StateValidation.class}
)//用哪个类里的校验规则
public @interface State {
//提供校验失败后的提示信息
String message() default "state参数的值只能是草稿或者已发布";
//指定分组
Class<?>[] groups() default {};
//负载 获取到State注解的附加信息 //一般用不到不用管
Class<? extends Payload>[] payload() default {};
//注解实现类
package com.di.bigevent.validation;
import com.di.bigevent.anno.State;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
public class StateValidation implements ConstraintValidator<State,String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
//提供校验规则
if(value==null)
{
return false;
}
if(value.equals("已发布")||value.equals("草稿")){
return true;
}
return false;
}
}