spring vaild 自定义注解过滤验证html
MyNotHtml.java
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by MATT on 5月11月0011.
*/
@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(value = RetentionPolicy.RUNTIME)
@Constraint(validatedBy= MyNotHtmlImpl.class)
public @interface MyNotHtml {
/**
* 这三个方法是必须要有的
*/
String message();
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default {};
}
MyNotHtmlImpl.java
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by MATT on 5月11月0011.
*/
public class MyNotHtmlImpl implements ConstraintValidator<MyNotHtml, String> {
private Logger logger = LoggerFactory.getLogger(getClass());
private static final String REG_STR = "<[^>]+>";
Pattern pattern = Pattern.compile(REG_STR);
public void initialize(MyNotHtml constraint) {
logger.info("校验初始化...");
}
public boolean isValid(String obj, ConstraintValidatorContext context) {
if (obj == null || "".equals(obj)) {
return true;
}
Matcher m = pattern.matcher(obj);
return !m.find();
}
}
用法
//评价内容
@NotBlank(message = "不能为空")
@MyNotHtml(message = "评论内容含有特殊字符")
private String reviewText;
@JsonIgnore
private String adminReply;
//发布审核结果:0未审核1.审核失败2.审核成功
网友评论