Spring Boot 2.X 如何添加攔截器?


最近使用SpringBoot2.X搭建了一個項目,大部分接口都需要做登錄校驗,所以打算使用注解+攔截器來實現,在此記錄下實現過程。

 

一、實現原理

1. 自定義一個注解@NeedLogin,如果接口需要進行登錄校驗,則在接口方法或類方法上添加該注解。
2. 登錄攔截器LoginInterceptor校驗接口的方法或類上是否有@NeedLogin注解,有注解則進行登錄校驗。

二、主要代碼

1. NeedLogin注解代碼

package com.example.helloSpringBoot.annotation;

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

/**
 * 登錄注解
 *
 * @Author: Java碎碎念
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface NeedLogin {
}

2. 登錄攔截器LoginInterceptor

package com.example.helloSpringBoot.config;

import com.example.helloSpringBoot.annotation.NeedLogin;
import com.example.helloSpringBoot.util.WxUserInfoContext;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 登錄攔截器
 *
 * @Author: Java碎碎念
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    //這個方法是在訪問接口之前執行的,我們只需要在這里寫驗證登陸狀態的業務邏輯,就可以在用戶調用指定接口之前驗證登陸狀態了
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            NeedLogin needLogin = ((HandlerMethod) handler).getMethodAnnotation(NeedLogin.class);
            if (null == needLogin) {
                needLogin = ((HandlerMethod) handler).getMethod().getDeclaringClass()
                        .getAnnotation(NeedLogin.class);
            }
            // 有登錄驗證注解,則校驗登錄
            if (null != needLogin) {
                WxUserInfoContext curUserContext = (WxUserInfoContext) request.getSession()
                        .getAttribute("curUserContext");
                //如果session中沒有,表示沒登錄
                if (null == curUserContext) {
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().write("未登錄!");
                    return false;
                }
            }

        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}

3. 配置攔截器

package com.example.helloSpringBoot.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * WebConfig
 *
 * @Author: Java碎碎念
 *
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 自定義攔截器,添加攔截路徑和排除攔截路徑
        registry.addInterceptor(loginInterceptor).addPathPatterns("/**");
    }
}

三、驗證代碼

HelloController中添加兩個方法,testNeedLogin()方法添加登錄攔截,testNoLogin()方法不需要登錄攔截。

package com.example.helloSpringBoot.controller;

import com.example.helloSpringBoot.annotation.NeedLogin;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    /**
     * 測試不 需要登錄
     *
     *
     */
    @RequestMapping("/testNoLogin")
    public String testNoLogin (){
        return "調用成功,此接口不需要登錄校驗!-Java碎碎念!";
    }

    /**
     * 測試需要登錄
     *
     *
     */
    @NeedLogin
    @RequestMapping("/testNeedLogin")
    public String testNeedLogin (){
        return "testNeedLogin!";
    }
}

testNeedLogin運行截圖如下:

testNoLogin運行截圖如下:

  

上述三步操作完成后即可實現登錄攔截,有問題歡迎留言溝通哦!

完整源碼地址:https://github.com/suisui2019/helloSpringBoot

 

推薦閱讀

1.Spring Boot 2.X 如何優雅的解決跨域問題?
2.Redis Cluster搭建高可用Redis服務器集群
3.為什么單線程的Redis這么快?
4.Spring Boot集成spring session實現session共享
5.Spring Boot入門-快速搭建web項目
6.Spring Boot2.0整合Redis
7.一篇文章搞定SpringMVC參數綁定
8.SpringMVC+Mybatis 如何配置多個數據源並切換?

 

限時領取免費Java相關資料,涵蓋了Java、Redis、MongoDB、MySQL、Zookeeper、Spring Cloud、Dubbo/Kafka、Hadoop、Hbase、Flink等高並發分布式、大數據、機器學習等技術。

資料傳送門:  https://mp.weixin.qq.com/s/u2b_NVNuMuAPE0w4lc45fw

關注下方公眾號即可免費領取:

Java碎碎念公眾號


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM