<mvc:annotation-driven/> 會註冊兩個內部攔截器(ConversionServiceExposingInterceptor、ResourceUrlEncodingInterceptor),若配置不當會導致自定義攔截器不生效。本文記錄排查過程與完整解決方案。
<mvc:interceptors> 但自定義攔截器不執行<mvc:annotation-driven/> 必須聲明,但會改變攔截器鏈順序@Controller,導致 Bean 創建兩次<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:context="https://www.springframework.org/schema/context"
xmlns:mvc="https://www.springframework.org/schema/mvc"
xsi:schemaLocation="...">
<!-- 1. 默認 Servlet 處理靜態資源 -->
<mvc:default-servlet-handler/>
<!-- 2. 註解驅動(必須) -->
<mvc:annotation-driven/>
<!-- 3. 掃描 Controller,排除 Service 等 -->
<context:component-scan base-package="com.muke.controller" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 4. 視圖解析器 -->
<bean id="viewResolverJsp" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 5. 關鍵:攔截器配置,正確排除靜態資源 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<!-- 排除靜態資源目錄 -->
<mvc:exclude-mapping path="/html/**"/>
<mvc:exclude-mapping path="/back_css/**"/>
<mvc:exclude-mapping path="/back_js/**"/>
<mvc:exclude-mapping path="/back_img/**"/>
<mvc:exclude-mapping path="/back_other/**"/>
<mvc:exclude-mapping path="/layer/**"/>
<mvc:exclude-mapping path="/laypage/**"/>
<bean class="com.muke.springMVC.interceptors.DefaultInterceptors"/>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/manage/menuBar/**"/>
<bean class="com.muke.springMVC.interceptors.ManagerPowerInterceptors"/>
</mvc:interceptor>
</mvc:interceptors>
</beans>
<!-- applicationContext.xml -->
<context:component-scan base-package="com.muke" use-default-filters="false">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
原則:Spring 掃描 Service/DAO/Component,Spring MVC 只掃描 Controller,互斥配置避免重複代理。
mvc:exclude-mapping 按目錄/後綴排除<mvc:default-servlet-handler/> 讓容器原生處理靜態資源org.springframework.web DEBUG 日誌,觀察攔截器鏈執行順序攔截器失效多因配置順序、靜態資源衝突、重複掃描引起。遵循「分離掃描、排除靜態、啟用默認 Servlet」三原則,配合結構化日誌調試,可徹底解決此類問題。