亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

SpringBoot攔截器不生效的問題解決

 更新時間:2024年09月05日 08:52:44   作者:True_aFalse  
很多開發(fā)者會遇到一個常見的問題,攔截器配置了卻不生效,本文主要介紹了SpringBoot攔截器不生效的問題解決,具有一定的參考價值,感興趣的可以了解一下

在使用 Spring Boot 開發(fā) Web 應(yīng)用時,我們常常需要使用攔截器(Interceptor)來對請求進行預(yù)處理。例如,驗證用戶是否登錄。然而,很多開發(fā)者會遇到一個常見的問題:攔截器配置了卻不生效。本文將討論一種常見的原因及其解決方案——將配置類移入正確的包下。

問題描述

我們創(chuàng)建了一個 LoginCheckInterceptor 類,并在 WebConfig 類中進行注冊。但是,啟動應(yīng)用后發(fā)現(xiàn)攔截器并沒有生效。

示例代碼:

LoginCheckInterceptor 類:

package com.itheima.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        String url = req.getRequestURL().toString();
        log.info("請求的url: {}", url);

        if (url.contains("login")) {
            log.info("登錄操作, 放行...");
            return true;
        }

        String jwt = req.getHeader("token");

        if (!StringUtils.hasLength(jwt)) {
            log.info("請求頭token為空,返回未登錄的信息");
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return false;
        }

        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失敗, 返回未登錄錯誤信息");
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return false;
        }

        log.info("令牌合法, 放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle ...");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}

WebConfig 類:

package com.config;

import com.itheima.interceptor.LoginCheckInterceptor;
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;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private LoginCheckInterceptor loginCheckInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/**");
    }
}

解決方案

將 WebConfig 類移到 itheima 包下即可解決問題。原因在于 Spring Boot 的默認(rèn)包掃描機制。

原因分析

Spring Boot 使用 @SpringBootApplication 注解的主應(yīng)用類啟動應(yīng)用。該注解包含了 @ComponentScan,默認(rèn)掃描主應(yīng)用類所在包及其子包中的所有組件。如果 WebConfig 類不在主應(yīng)用類所在包或其子包下,Spring Boot 將無法自動掃描到它,從而導(dǎo)致攔截器不生效。

解決方法

將 WebConfig 類移到 com.itheima 包下,確保其在主應(yīng)用類的掃描路徑內(nèi)。

調(diào)整后的目錄結(jié)構(gòu):

src/main/java
 └── com
     └── itheima
         ├── MyApplication.java
         ├── interceptor
         │   └── LoginCheckInterceptor.java
         └── config
             └── WebConfig.java

代碼調(diào)整

將 WebConfig 類從 com.config 包移到 com.itheima.config 包下:

package com.itheima.config;

import com.itheima.interceptor.LoginCheckInterceptor;
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;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private LoginCheckInterceptor loginCheckInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/**");
    }
}

其他解決方案

如果不想移動配置類,還可以通過以下方法顯式指定掃描路徑:

1. 使用 @ComponentScan 注解指定掃描包

package com.itheima;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = {"com.itheima", "com.config"})
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

2. 使用 @Import 注解導(dǎo)入配置類

package com.itheima;

import com.itheima.config.WebConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;

@SpringBootApplication
@Import(WebConfig.class)
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

通過這些方式,可以確保 Spring Boot 正確掃描和加載攔截器配置類,使攔截器生效。

結(jié)論

在使用 Spring Boot 開發(fā) Web 應(yīng)用時,正確配置包掃描路徑非常重要。確保配置類在主應(yīng)用類的掃描路徑內(nèi),可以有效解決攔截器不生效的問題。希望這篇文章能夠幫助大家更好地理解 Spring Boot 的包掃描機制,并順利解決開發(fā)中遇到的問題。

到此這篇關(guān)于SpringBoot攔截器不生效的問題解決的文章就介紹到這了,更多相關(guān)SpringBoot攔截器不生效內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java線程變量ThreadLocal詳細(xì)解讀

    Java線程變量ThreadLocal詳細(xì)解讀

    這篇文章主要介紹了Java線程變量ThreadLocal詳細(xì)解讀,多線程訪問同一個變量的時候,很容易出現(xiàn)問題,特別是多線程對一個共享變量進行寫入的時候,為了線程的安全在進行數(shù)據(jù)寫入時候會進行數(shù)據(jù)的同步,需要的朋友可以參考下
    2024-01-01
  • Java1.7全網(wǎng)最深入HashMap源碼解析

    Java1.7全網(wǎng)最深入HashMap源碼解析

    HashMap 是一個散列表,它存儲的內(nèi)容是鍵值對(key-value)映射。HashMap 實現(xiàn)了 Map 接口,根據(jù)鍵的 HashCode 值存儲數(shù)據(jù),具有很快的訪問速度,最多允許一條記錄的鍵為 nul
    2021-11-11
  • 使用Spring Cache時設(shè)置緩存鍵的注意事項詳解

    使用Spring Cache時設(shè)置緩存鍵的注意事項詳解

    在現(xiàn)代的Web應(yīng)用中,緩存是提高系統(tǒng)性能和響應(yīng)速度的重要手段之一,Spring框架提供了強大的緩存支持,通過??@Cacheable??、??@CachePut??、??@CacheEvict??等注解可以方便地實現(xiàn)緩存功能,本文給大家介紹了使用Spring Cache時設(shè)置緩存鍵的注意事項
    2025-01-01
  • java中使用interrupt通知線程停止詳析

    java中使用interrupt通知線程停止詳析

    這篇文章主要介紹了java中使用interrupt通知線程停止詳析,文章介紹的是使用interrupt來通知線程停止運行,而不是強制停止,詳細(xì)內(nèi)容需要的小伙伴可以參考一下
    2022-09-09
  • SpringBoot靜態(tài)資源CSS等修改后再運行無效的解決

    SpringBoot靜態(tài)資源CSS等修改后再運行無效的解決

    這篇文章主要介紹了SpringBoot靜態(tài)資源CSS等修改后再運行無效的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • 淺析Java getResource詳細(xì)介紹

    淺析Java getResource詳細(xì)介紹

    這篇文章主要介紹了Java getResource 講解,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-09-09
  • Required?request?body?is?missing的問題及解決

    Required?request?body?is?missing的問題及解決

    這篇文章主要介紹了Required?request?body?is?missing的問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • Java的四種引用方式

    Java的四種引用方式

    這篇文章主要介紹了Java的四種引用方式,Java的引用方式主要包括強引用、軟引用、弱引用、虛引用;下面文章便來詳細(xì)介紹這四種引用方式,需要的朋友可以參考一下
    2021-10-10
  • SpringBoot@Profile注解和Spring?EL(多環(huán)境注入)

    SpringBoot@Profile注解和Spring?EL(多環(huán)境注入)

    為了方便, Spring還提供了 Profile機制, 使我們可以很方便地實現(xiàn)各個環(huán)境之間的切換,在使用DI來依賴注入的時候,能夠根據(jù)@profile標(biāo)明的環(huán)境,將注入符合當(dāng)前運行環(huán)境的相應(yīng)的bean,本文通過示例代碼介紹SpringBoot@Profile注解和Spring?EL,需要的朋友可以參考下
    2024-02-02
  • JAVA項目常用異常處理匯總

    JAVA項目常用異常處理匯總

    這篇文章主要介紹了JAVA項目常用異常處理匯總,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-11-11

最新評論