validation.StateValidation
package com.lin.springboot01.validation;
import com.lin.springboot01.anno.State;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
public class StateValidation implements ConstraintValidator {
/**
*
* @param value 将来要校验的数据
* @param context 如果返回false,则校验不通过,如果返回true,则校验通过
* @return
*/
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
//提供校验规则
if (value==null){
return false;
}
if (value.equals("已发布") || value.equals("草稿")){
return true;
}
return false;
}
}
anno.State
package com.lin.springboot01.anno;
import com.lin.springboot01.validation.StateValidation;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Documented //元注解
@Target({FIELD})//元注解
@Retention(RUNTIME) //元注解
@Constraint(validatedBy = {StateValidation.class}) //指定提供校验的类
public @interface State {
//提供校验失败后的提示信息
String message() default "State的值只能是已发布或者草稿";
//指定分组
Class>[] groups() default {};
//负载,获取到State注解的附加信息
Class extends Payload>[] payload() default {};
}
Article
package com.lin.springboot01.pojo;
import com.lin.springboot01.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;
@NotEmpty
@Pattern(regexp = "^\\S{1,16}$")
private String title;
@NotEmpty
private String content;
@NotEmpty
@URL
private String coverImg;
@State //这个就是我们自定义的数据校验的注解
private String state;
@NotNull
private Integer categoryId;
private Integer createUser;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
ArticleController
@RestController
@RequestMapping("/article")
public class ArticleController {
@Autowired
private ArticleService articleService;
@PostMapping
//@Validated pojo中的数据校验生效
public Result add(@RequestBody @Validated Article article){
articleService.add(article);
return Result.success();
}
}