- 定义注解
package com.futao.springmvcdemo.annotation; import com.futao.springmvcdemo.annotation.impl.IllegalValueCheckImpl; import com.futao.springmvcdemo.model.entity.constvar.ErrorMessage; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.*; /** * @author futao * Created on 2018/9/25. */ //关联解析类, 检验逻辑 @Constraint(validatedBy = IllegalValueCheckImpl.class) @Target(value = {ElementType.PARAMETER}) @Retention(value = RetentionPolicy.RUNTIME) @Documented public @interface IllegalValueCheck { /** * 拦截的字符串 * * @return */ String forbidden() default "mmp"; /** * 验证不通过时的错误提示信息 * * @return */ String message() default ErrorMessage.CONTAIN_ILLEGAL_PARAMETER; Class<?>[] groups() default {}; /** * 变量名称 payload不可变 * 否则会抛出异常`javax.validation.ConstraintDefinitionException: HV000074` * * @return */ Class<? extends Payload>[] payload() default {}; }
- 定义注解的实现逻辑类
package com.futao.springmvcdemo.annotation.impl; import com.futao.springmvcdemo.annotation.IllegalValueCheck; import org.apache.commons.lang3.ObjectUtils; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; /** * @author futao * Created on 2018/9/25. * 敏感词检测 */ public class IllegalValueCheckImpl implements ConstraintValidator<IllegalValueCheck, String> { private String forbidden; /** * 初始化 * * @param constraintAnnotation */ @Override public void initialize(IllegalValueCheck constraintAnnotation) { //获取禁止的词汇 this.forbidden = constraintAnnotation.forbidden(); } /** * 检验逻辑 * * @param value * @param context * @return */ @Override public boolean isValid(String value, ConstraintValidatorContext context) { if (!ObjectUtils.allNotNull(value)) { return true; } if (value.contains(forbidden)) { return false; } return true; } }
- 测试
3.1使用默认的敏感词
/** * 添加评论 * * @param content * @return */ @PostMapping(path = "addReview") public SingleValueResult addReview( @RequestParam("content") @IllegalValueCheck String content) { SingleValueResult result = new SingleValueResult(content); return result; }
3.2灵活使用敏感词
/** * 添加评论 * * @param content * @return */ @PostMapping(path = "addReview") public SingleValueResult addReview( @RequestParam("content") @IllegalValueCheck(forbidden = "亚索") String content) { SingleValueResult result = new SingleValueResult(content); return result; }
写代码的时候发现:如果Controller层返回的对象没有getter和setter会抛出org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
异常