一、mvc:annotation-driven的作用
Spring 3.0.x中使用了mvc:annotation-driven后,默認會幫我們注冊默認處理請求,參數和返回值的類,其中最主要的兩個類:DefaultAnnotationHandlerMapping 和 AnnotationMethodHandlerAdapter ,分別為HandlerMapping的實現類和HandlerAdapter的實現類,從3.1.x版本開始對應實現類改為了RequestMappingHandlerMapping和RequestMappingHandlerAdapter。
HandlerMapping的實現類的作用
實現類RequestMappingHandlerMapping,它會處理
@RequestMapping 注解,並將其注冊到請求映射表中。
HandlerAdapter的實現類的作用
實現類RequestMappingHandlerAdapter,則是處理請求的適配器,確定調用哪個類的哪個方法,並且構造方法參數,返回值。
當配置了mvc:annotation-driven/后,Spring就知道了我們啟用注解驅動。然后Spring通過context:component-scan/標簽的配置,會自動為我們將掃描到的
@Component,@Controller,@Service,@Repository等注解標記的組件注冊到工廠中,來處理我們的請求。
二、使用的場景:
如果在web.xml中servlet-mapping的url-pattern設置的是/,而不是如.do。表示將所有的文件,包含靜態資源文件都交給spring mvc處理。就需要用到<mvc:annotation-driven />了。如果不加,DispatcherServlet則無法區分請求是資源文件還是mvc的注解,而導致controller的請求報404錯誤。
<servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
基礎的springmvc.xml的配置:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/jdbchttp://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!--掃描Controller,並將其生命周期納入Spring管理--> <context:annotation-config/> <context:component-scan base-package="com.how2java.controller"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--注解驅動,以使得訪問路徑與方法的匹配可以通過注解配置--> <mvc:annotation-driven /> <!--通過location,可以重新定義資源文件的位置--> <mvc:resources mapping="/styles/**" location="/WEB-INF/resource/styles/"/> <!--靜態頁面,如html,css,js,images可以訪問--> <mvc:default-servlet-handler /> <!-- 視圖定位到/WEB/INF/jsp 這個目錄下 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>