一、SpringMVC簡介
SpringMVC也叫Spring Web mvc,屬于表現層的框架。Spring MVC是Spring框架的一部分,是在Spring3.0后發布的
二、Spring結構圖
三、SpringMVC架構圖
四、SpringMVC請求流程圖
五、SpringMVC請求流程文字描述:
request-------->DispatcherServler(中央調度器/前端控制器)-----> HandlerMapping(處理器映射器)------>返回一個執行鏈----->將執行鏈轉交給HandlerAdaptor(處理器適配器)----->調度Handler(處理器)-----> ModelAndView----->先將結果交給HandlerAdaptor,然后再由HandlerAdaptor轉交給 DispatcherServler--------->DispatcherServler調度ViewResolver(視圖解析器)---->交給DispatcherServler-------> 尋找View---->View做出響應(response)
六、第一個入門案例:
案例:用戶提交一個請求,服務器端處理器在接收到這個請求后,給出一條歡迎信息,在頁面中顯示。
步驟:
①在web.xml中配置前端控制器
②處理器映射器(HandlerMapping)
③處理器適配器 (HandlerAdaptor)
④處理器
⑤視圖解析器(ViewResolver)
1、引入jar文件
2、注冊中央調度器[Web.xml]
3、控制器
4、applicationContext.xml配置文件。配置視圖解析器以及注冊處理器
5、jsp頁面
實現效果:
七、關于urlpattern
最好配成*.do
不能配成/* ===[無法訪問*.jsp等動態資源]
最好也不要配成/ === [無法訪問靜態資源]
不得不配成/
如果url-pattern配成/*,則無法訪問動態資源,出現404. 如果配成/ ,則無法訪問靜態資源,圖片無法顯示。
不能配成/*緣由:
DispatcherServlet會將向動態頁面請求,即向jsp頁面的跳轉請求也當做是一個普通的Controller請求。中央調度器會調用處理器映射器為其查找相應的處理器。當然是找不到的。jsp頁面會報404錯誤
結論:/*會攔截動態資源
不能配成/:
方案一:使用Tomcat默認的Servlet解決
方案二:使用MVC的default-servlet-handler
會將對靜態資源的訪問請求通過HandlerMapping映射到默認Servlet請求處理器DefaultServletRequestHandler對象。而該處理器調用了Tomcat的DefaultServlet來處理靜態資源的訪問請求。當然需要引入mvc約束
方式三:使用MVC的resource解決
在Spring3.0.4之后,Spring定義了專門用于處理靜態資源請求的處理器ResourceHttpRequestHandler。并且添加了<mvc:resources/>標簽,專門用于解決靜態資源無法訪問問題。
Location:靜態資源所在目錄
mapping: 對資源的請求
注意:需要Tomcat7支持
效果圖:
八、配置式開發--BeanNameUrlHandlerMapping
<!-- 配置處理器映射器 --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
配置式開發--SimpleUrlHandlerMapping
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/hello.do">firstController</prop> <prop key="/sayhello.do">firstController</prop> </props> </property> </bean>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="urlMap"> <map> <entry key="/hello.do"> <value>firstController</value> </entry> <entry key="/sayhello.do"> <value>firstController</value> </entry> </map> </property> </bean>
文章列表