這幾天在做專案,從其他專案中複製貼上攔截器的程式碼,然後修修改改,但是攔截器一直不起作用,請求來了進不去,最後發現是我寫錯了,程式碼如下:
配置檔案:
application.yml
server:
port: 8080
servlet:
context-path: /api/v1
#springboot的配置
spring:
datasource: #定義資料來源
#127.0.0.1為本機測試的ip,3306是mysql的埠號。serverTimezone是定義時區,照抄就好,mysql高版本需要定義這些東西
#useSSL也是某些高版本mysql需要問有沒有用SSL連線
url: jdbc:mysql://127.0.0.1:3306/testdb?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong&useAffectedRows=true
username: root #資料庫使用者名稱,root為管理員
password: 12345678 #該資料庫使用者的密碼
# 使用druid資料來源
type: com.alibaba.druid.pool.DruidDataSource
thymeleaf:
encoding: UTF-8 #編碼規範 預設
cache: false #開發階段建議關閉快取
prefix: classpath:/templates/
suffix: .html
mode: LEGACYHTML5 #用非嚴格的HTML5 預設是HTML5
servlet:
content-type: text/html
# mybatis-plus相關配置
mybatis-plus:
# xml掃描,多個目錄用逗號或者分號分隔(告訴 Mapper 所對應的 XML 檔案位置)
mapper-locations: classpath:mapper/*.xml
# 以下配置均有預設值,可以不設定
global-config:
db-config:
#主鍵型別 AUTO:"資料庫ID自增" INPUT:"使用者輸入ID",ID_WORKER:"全域性唯一ID (數字型別唯一ID)", UUID:"全域性唯一ID UUID";
id-type: auto
#欄位策略 IGNORED:"忽略判斷" NOT_NULL:"非 NULL 判斷") NOT_EMPTY:"非空判斷"
field-strategy: NOT_EMPTY
#資料庫型別
db-type: MYSQL
configuration:
# 是否開啟自動駝峰命名規則對映:從資料庫列名到Java屬性駝峰命名的類似對映
map-underscore-to-camel-case: true
# 如果查詢結果中包含空值的列,則 MyBatis 在對映的時候,不會對映這個欄位
call-setters-on-nulls: true
# 這個配置會將執行的sql列印出來,在開發或測試的時候可以用
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 日誌配置
logging:
group:
tomcat:
- org.apache.catalina
- org.apache.coyote
- org.apache.tomcat
# pre-defined
level:
tomcat: INFO
web: DEBUG
sql: DEBUG
WebConfig.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 攔截器
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private RequestHandlerInterceptor requestHandlerInterceptor;
@Value("${server.servlet.context-path}")
private String contextPath;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(requestHandlerInterceptor)
// 需要排除contextPath的值
.addPathPatterns(contextPath + "/**") // 即/api/v1/**
.excludePathPatterns(Consts.EXCLUDE_PATH_PATTERNS);
}
}
RequestHandlerInterceptor.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
/**
* @Author SingleKey
* @Date 2024/7/28 8:27
*/
@Component
public class RequestHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
System.out.println("\n-------- RequestHandlerInterceptor.preHandle --- ");
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("\n-------- RequestHandlerInterceptor.postHandle --- ");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("\n-------- RequestHandlerInterceptor.afterCompletion --- ");
}
}
乍一看好像沒有問題,錯誤的地方是WebConfig.java的addPathPatterns(contextPath + "/**")這段程式碼,如果在配置檔案中設定了context-path,那就不能再在這麼寫:addPathPatterns(contextPath + "/**"),不然將永遠匹配不到,其實也是自己debug能力的欠缺,以及對SpringBoot的不夠熟悉導致的,今日記下這個問題,供大家參考。
server:
port: 8080
servlet:
context-path: /api/v1