SpringBoot攔截器不生效的問(wèn)題解決
在使用 Spring Boot 開發(fā) Web 應(yīng)用時(shí),我們常常需要使用攔截器(Interceptor)來(lái)對(duì)請(qǐng)求進(jìn)行預(yù)處理。例如,驗(yàn)證用戶是否登錄。然而,很多開發(fā)者會(huì)遇到一個(gè)常見的問(wè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 開發(fā) Web 應(yīng)用時(shí),正確配置包掃描路徑非常重要。確保配置類在主應(yīng)用類的掃描路徑內(nèi),可以有效解決攔截器不生效的問(wèn)題。希望這篇文章能夠幫助大家更好地理解 Spring Boot 的包掃描機(jī)制,并順利解決開發(fā)中遇到的問(wèn)題。
到此這篇關(guān)于SpringBoot攔截器不生效的問(wèn)題解決的文章就介紹到這了,更多相關(guān)SpringBoot攔截器不生效內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一個(gè)Java中BigDecimal的問(wèn)題記錄
這篇文章主要給大家介紹了關(guān)于Java中一個(gè)BigDecimal問(wèn)題的相關(guān)資料,通過(guò)文中介紹的方法可以很方便的解決BigDecimal進(jìn)行計(jì)算的時(shí)候不管怎么計(jì)算,最后得到的值都沒(méi)有變化的問(wèn)題,需要的朋友可以參考下2021-11-11
Java中EasyExcel使用自定義Converter處理方法詳解
EasyExcel自定義Converter是指在使用EasyExcel進(jìn)行Excel讀寫操作時(shí),可以自定義轉(zhuǎn)換器來(lái)處理一些不支持的數(shù)據(jù)類型,這篇文章主要給大家介紹了關(guān)于Java中EasyExcel使用自定義Converter處理的相關(guān)資料,需要的朋友可以參考下2024-08-08
vue數(shù)據(jù)響應(yīng)式原理重寫函數(shù)實(shí)現(xiàn)數(shù)組響應(yīng)式監(jiān)聽
Vue的通過(guò)數(shù)據(jù)劫持的方式實(shí)現(xiàn)數(shù)據(jù)的雙向綁定,即使用Object.defineProperty()來(lái)實(shí)現(xiàn)對(duì)屬性的劫持,但是Object.defineProperty()中的setter是無(wú)法直接實(shí)現(xiàn)數(shù)組中值的改變的劫持行為的,需要的朋友可以參考下2023-05-05
詳解SSM框架下結(jié)合log4j、slf4j打印日志
本篇文章主要介紹了詳解SSM框架下結(jié)合log4j、slf4j打印日志,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-11-11

