Spring boot 添加拦截器

以实现用户登录权限验证添加拦截器为例

1、创建注解

创建require包,在该包下创建LoginRequired类

package com.example.require;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {

    boolean loginSuccess() default true;
}

2、创建拦截器

创建interceptor包,在该包下创建OnlineInterceptor类(拦截逻辑代码写在这个函数里

package com.example.interceptor;

import com.example.require.LoginRequired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

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

public class OnlineInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 拦截处理代码
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod method = (HandlerMethod) handler;
        LoginRequired loginRequired = method.getMethodAnnotation(LoginRequired.class);
        System.out.println("进拦截器啦啦啦啦啦啦啦啦!!!");
        if (null != loginRequired)
        {
            //这个是需要拦截的方法
            //这里写拦截代码
        } else
        {
            //这个是不需要拦截的方法
            return true;
        }
        //返回true通过,返回false拦截
        return true;
    }
}

3、注册拦截器

创建WebAppConfig类配置拦截器

package com.example;

import com.example.interceptor.OnlineInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebAppConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册自己的拦截器
        registry.addInterceptor(new OnlineInterceptor()).
                addPathPatterns("/**").//设置拦截的请求路径
                excludePathPatterns("/static/**","/index");//设置不拦截的请求路径
    }
}

文件存放路径:

 

4、使用

在需要拦截的方法上加上@LoginRequired注解即可。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值