关于sofaboot拦截器的问题

我的问题:一个sofaboot项目中,按正常springboot项目那样写拦截器或者过滤器都不好用

我的写法

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //每一个项目对于登陆的实现逻辑都有所区别,我这里使用最简单的Session提取User来验证登陆。
        //如果session中没有user,表示没登陆
        log.info("");
        return true;
    }

}
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
    @Autowired
    private LoginInterceptor loginInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // addPathPatterns("/**") 表示拦截所有的请求,
        // excludePathPatterns("/login", "/register") 表示除了登陆与注册之外,因为登陆注册不需要登陆也可以访问
        registry.addInterceptor(loginInterceptor).addPathPatterns("/service/00000/*").excludePathPatterns("/login", "/register");
    }
}

 我访问的路径

http://127.0.0.1:12100/m-pf-productfactory/service/00000/37000008

不管addPathPatterns后边是什么路径是一个*还是两个*都试过

filter也试过  都不好使

没办法用切面写的

如下

@Aspect
@Configuration
@Slf4j
@Component
public class LoginAspect {
    // 第一个*代表返回类型不限
    // 第二个*代表所有类
    // 第三个*代表所有方法
    // (..) 代表参数不限
    @Pointcut("execution(public * com.wish.biz.pf.productfactory.srv.c04320.*.*(..)) && !execution(public * com.wish.biz.pf.productfactory.srv.c04320.Srv37000048.*(..))")
    //Srv37000048为登陆类
    public void pointCut(){};

    @Around(value = "pointCut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
            if(false){//根据业务逻辑改 可以改成true测试
                throw new BizRuntimeException(MpfProductfactoryErrCodeBussCheck.ERR_CODE_BUSS_CHECK_PF_000007,"1111111");
            }else {
                return proceedingJoinPoint.proceed();
            }
    }
}

如上切面方法,有两点可以学习的地方

1.排除除某个类之外的拦截

& !execution

 @Pointcut("execution(public * com.wish.biz.pf.productfactory.srv.c04320.*.*(..)) && !execution(public * com.wish.biz.pf.productfactory.srv.c04320.Srv37000048.*(..))")

2.  @Before和@Around

之前用@Before   启动报错

ProceedingJoinPoint is only supported for around advice

 而且JointPoint没有proceed方法

发布了50 篇原创文章 · 获赞 2 · 访问量 9412

猜你喜欢

转载自blog.csdn.net/qq_35653822/article/details/104254419