Spring MVC
Spring MVC介紹
- 什麼是MVC
它是Spring框架的一部分,負責表示層 - MVC的好處
- MVC設計模式
引入MVC框架
- 沒有使用MVC框架時候的不足
請求參數封裝很麻煩
結果視圖耦合性強(比如xxx.jsp裏邊不知道有多少亂七八糟的頁面)
url和(controller裏的方法)映射不方便(用註解直接填url)
controller的實現有約束 - MVC和SpringMVC
MVC是一種架構,是一種設計思想
而SpringMVC是這種架構下的MVC層的一個框架(工具類)
Spring MVC 的架構
- MVC框架 接收請求,獲取數據,分配任務,結果轉向(之前在servlet做)
高級框架的底層都是JavaEE規範(servlet、cookies、session等等)
導包
邏輯鏈
web.xml中初始化DispatcherServlet,並且用init-param說明spring的配置文件,告訴Servlet去這裏創建Bean,
在web.xml配置核心控制器DispatcherServlet
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"
metadata-complete="true">
<!--你要調用的核心控制器的id 和全類名DispatcherServlet-->
<servlet>
<servlet-name>springmvcservlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--初始化參數,將applicationContext.xml傳給contextConfigLocation-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
</servlet>
<!--你要調用的核心控制器的id和能夠訪問到這個servlet的url-->
<servlet-mapping>
<servlet-name>springmvcservlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
在Springmvc.xml(src文件夾裏的xml文件,沿用之前的applicationContext.xml)配置Spring mvc依賴的Bean
實現請求處理類,並且配置訪問URL
- 瀏覽器中輸入了hello.do,由於已經配置了BeanNameUrlHandlerMapping,它會幫你找到hello.do對應的handler
而handler是如何實現的呢? - 繼承org.springframework.web.servlet.mvc.Controller,重寫方法
@Controller
public class FirstController implements org.springframework.web.servlet.mvc.Controller {
@Autowired
Service myservice;
public void test(){
System.out.println("haha12345");
}
@Override
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
System.out.println("haha12345");
return null;
}
}
擼一遍邏輯
- 先在web.xml中配核心servlet——DispatcherServlet;
- 用戶輸入URL,DispatcherServlet接收到以後轉向裏邊配置好的contextConfigLocation,轉向它的value(applicationContext.xml),獲得spring的BeanContainer的控制權,可以獲得Bean;
- 實例化applicationContext.xml中的bean,其中的HandlerMapping根據你輸入的url轉向名叫url的bean(這個bean繼承了controller類,並且重寫了handleRequest方法),並且通過HandlerAdaper找到對應的handler方法進行處理;
- HandlerAdaper把ModelAndView傳給核心,核心給ViewResolver進行視圖解析、View進行數據填充,最後把生成的結果保存咋response裏邊返回給用戶。