欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot攔截器不生效的問(wèn)題解決

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

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

問(wèn)題描述

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

示例代碼:

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("請(qǐng)求的url: {}", url);

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

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

        if (!StringUtils.hasLength(jwt)) {
            log.info("請(qǐng)求頭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("解析令牌失敗, 返回未登錄錯(cuò)誤信息");
            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 包下即可解決問(wèn)題。原因在于 Spring Boot 的默認(rèn)包掃描機(jī)制。

原因分析

Spring Boot 使用 @SpringBootApplication 注解的主應(yīng)用類啟動(dòng)應(yīng)用。該注解包含了 @ComponentScan,默認(rèn)掃描主應(yīng)用類所在包及其子包中的所有組件。如果 WebConfig 類不在主應(yīng)用類所在包或其子包下,Spring Boot 將無(wú)法自動(dòng)掃描到它,從而導(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("/**");
    }
}

其他解決方案

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

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);
    }
}

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

結(jié)論

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

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

相關(guān)文章

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

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

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

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

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

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

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

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

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

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

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

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

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

    Required?request?body?is?missing的問(wèn)題及解決

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

    Java的四種引用方式

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

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

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

    JAVA項(xiàng)目常用異常處理匯總

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

最新評(píng)論