SpringBoot 接收查询参数,Mysql模糊查询 包含 % _等特殊字符 解决方案

% _MySql中的特殊字符,如需对这几个字符在Mysql中进行模糊搜索则需要进行转义处理 \_ \%

SpringBoot接收查询参数,然后拦截做特殊处理

注解
@Target({METHOD, FIELD, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
public @interface LikeCondition {
}
切面
@Aspect
@Component
@Slf4j
public class LikeConditionAspect {

    @Pointcut(value = "@annotation(cn.worken.mobile.config.common.annotation.LikeCondition)")
    public void pointcut() {

    }

    @Around(value = "pointcut() ")
    public Object inject(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs();
        if(args.length>0){
            /**
             *  处理 @RequestBody 和 对象传参等
             */
            for (int i = 0; i < args.length; i++) {
                Class<?> aClass = args[i].getClass();
                Field[] declaredFields = aClass.getDeclaredFields();
                for (Field declaredField : declaredFields) {
                    LikeCondition annotation = declaredField.getAnnotation(LikeCondition.class);
                    if(annotation != null){
                        declaredField.setAccessible(true);
                        Object field = ReflectionUtils.getField(declaredField,args[i]);
                        ReflectionUtils.setField(declaredField,args[i],replaceLikeCondition(field));
                    }
                }
            }
            /**
             *  处理 @RequestParam @PathVariable 相关的参数
             */
            MethodSignature signature = (MethodSignature) pjp.getSignature();
            Parameter[] parameters = signature.getMethod().getParameters();
            for (int i = 0; i < parameters.length; i++) {
                Parameter parameter=parameters[i];
                LikeCondition annotation = parameter.getAnnotation(LikeCondition.class);
                if(annotation != null){
                    args[i] = replaceLikeCondition(args[i]);
                }
            }
        }
        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed(args);
        return result;
    }

    static Object replaceLikeCondition(Object arg){
        if(arg instanceof String){
            String argStr = arg.toString();
            return  argStr.replaceAll("%","\\\\\\%")
                    .replaceAll("_","\\\\\\_");
        }
        return arg;
    }
}
使用

在请求方法前和 Req中的具体参数上 加上 注解 @LikeCondition

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值