Web.xml攔截所有:
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
spring-servlet.xml配置:
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/ckeditor/**" location="/ckeditor/" />
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/slide_img/**" location="/slide_img/" />
<!-- 啟用spring mvc 注解-->
<context:annotation-config />
<!-- 設置使用注解的類所在的jar包 -->
<context:component-scan base-package="com.zkl.controller"></context:component-scan>
<!-- 完成請求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<!-- 對模型視圖名稱的解析,在請求時模型視圖名稱添加前后綴 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
</bean>
就這配置,其他的都好好的,要考注解實現。
我直接訪問一個jsp然后跳轉到我的Controller發現直接404了。
然后我把攔截改為/*發現不404。可以直接訪問項目,也就是index頁面。但是不能直接訪問到jsp了。
說明 /*是攔截所有包括.jsp后綴。/不包含jsp。
我又將mvc:resources的標簽全部去掉,發現都正常了,但是訪問不到圖片了。說明圖片以及css和其他靜態資源被攔截了。
於是我去檢查其他地方,我猜測是spring-servlet.xml的問題。我進去后就找到了<context:annotation-config />這個標簽。這個是啟用注解的。
我百度了一番后發現配置這個的並不多 <mvc:annotation-driven /> 倒都是配置着。
我找到了這么一句話:
<mvc:annotation-driven/>
相當於注冊了DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter兩個bean,配置一些messageconverter。即解決了@Controller注解的使用前提配置。
<context:annotation-config/>
1)隱式地向Spring容器中注冊AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor 及 equiredAnnotationBeanPostProcessor 這 4 個 BeanPostProcessor。
在配置文件中使用<context:annotationconfig/>之前,必須在 <beans> 元素中聲明 context 命名空間<context:component-scan/>。
2)是對包進行掃描,實現注釋驅動Bean定義,同時將bean自動注入容器中使用。即解決了@Controller標識的類的bean的注入和使用。
<context:component-scan/>
配置項不但啟用了對類包進行掃描以實施注釋驅動 Bean 定義的功能,同時還啟用了注釋驅動自動注入的功能(即還隱式地在內部注冊了 AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor),因此當使用 <context:component-scan/> 后,除非需要使用PersistenceAnnotationBeanPostProcessor和equiredAnnotationBeanPostProcessor兩個Processor的功能(例如JPA等)否則就可以將 <context:annotation-config/> 移除了。