自定义注解校验参数

此方式并不是特别友好:

如果掌握程度可以的话可以看看我的另外一篇配置化方式:

校验规则引擎设计-校验中心化(改进版)_haohaounique的博客-CSDN博客_校验规则 设计

场景:自定义注解校验参数,写在类上的注解;针对某类型的校验

1.自定义注解,注解放在方法上:ElementType.METHOD,如果需要放在类上可以点进去看看枚举

2.自定义拦截器或者使用appliacatonContext做一些处理

import java.lang.annotation.*;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UserIdAnnotation {

    String userId();

}

拦截器:

import com.check.utils.UserIdAnnotation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * description:userId拦截器
 */
@Component
@Slf4j
public class UserIdInterceptHandler implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            UserIdAnnotation methodAnnotation = ((HandlerMethod) handler).getMethodAnnotation(UserIdAnnotation.class);
            if (methodAnnotation != null) {
                String userId = request.getParameter(methodAnnotation.userId());
                /**
                 * 判断redis缓存中是否存在,存在放行,不存在则拦截
                 */
                log.info("userId:{}", userId);
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}

使拦截器生效

import com.check.intercept.UserIdInterceptHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * description:
 */
@Component
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private UserIdInterceptHandler handler;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(handler);

    }
}

测试

@UserIdAnnotation(userId = "uuid")
@RequestMapping(value = "addOrderInfo")
public Map<String, Object> addOrderInfo(Map<String, Object> map) {
return null;
}

结果

2022-03-22 19:16:20.257  INFO 21672 --- [nio-9002-exec-1] c.c.intercept.UserIdInterceptHandler     : userId:null

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值