自定义一个注解@Xss。名字随意
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;/*** 自定义xss校验注解* * @author chfatech*/ @Retention(RetentionPolicy.RUNTIME) @Target(value = { ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER }) @Constraint(validatedBy = { XssValidator.class }) public @interface Xss {String message()default "不允许任何脚本运行";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {}; }
validator校验类:XssValidator。这个校验类要和上面的@Xss注解上的
@Constraint(validatedBy = { XssValidator.class })对应
import com.chfatech.common.utils.StringUtils; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.regex.Matcher; import java.util.regex.Pattern;/*** 自定义xss校验注解实现* * @author chfatech*/ public class XssValidator implements ConstraintValidator<Xss, String> {private static final String HTML_PATTERN = "<(\\S*?)[^>]*>.*?|<.*? />";@Overridepublic boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext){if (StringUtils.isBlank(value)){return true;}return !containsHtml(value);}public static boolean containsHtml(String value){Pattern pattern = Pattern.compile(HTML_PATTERN);Matcher matcher = pattern.matcher(value);return matcher.matches();} }
具体使用在某个字段上加上注解;形如:
@Data public class HomeQuery {@ApiModelProperty(name = "keyword",value = "搜索关键词")@Xss@SqlInject(message = "{exists.illge.word}")private String keyword;@ApiModelProperty(name = "sdgId",value = "sdg主键id")private Long sdgId; }
然后在控制层中增加@Validated注解校验就可以了
以上代码实现后。会自动针对某些增加了@Xss字符进行校验。如果想增加sql注入校验。以上方法类似