1. 程式人生 > >[spring mvc]<mvc: annotation-driven />的作用

[spring mvc]<mvc: annotation-driven />的作用

一、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>