1. 程式人生 > 其它 >ssm-03-spring-mvc-01-introduction

ssm-03-spring-mvc-01-introduction

ssm-03-spring-mvc-01-introduction

MVC框架簡介

在學習Spring MVC前,先來看看MVC框架。在經典的MVC模式中,M(Mode)指業務模型,V(View)指使用者頁面,C(Controller)指控制器,使用MVC的目的是讓 M和V的程式碼實現解耦,從而使一個程式可以有不同的表現形式。
V(View):指使用者看到並與之互動的介面;
M(Mode):指業務規則,返回了V檢視所需的資料;
C(Controller):接受使用者輸入呼叫對應M模型處理業務,並返回對應V檢視。

Spring MVC

通過Spring思想,將Web MVC整合,具有高度可配置等特點。隨著前後端分離思想的推出,越來越多的企業已將V(View)由傳統的JSP轉向新一代的前端框架,如 VUE。下面通過簡單的入門例子開始認識:

  1. 建立工程模組:


  2. 此時的乾淨工程目錄結構如下:

  3. 接下來需要將工程改造-新增框架支援:

  4. 選擇Spring MVCMaven

  5. 此時的工程目錄結構如下:

  6. 配置pom檔案:


  7. 由於maven版本的原因,子模組pom配置用統一的version時,可能會包紅線提示:Properties in parent definition are prohibited.
    不過不影響工程的執行,如果有強迫症看不下去,可以升級maven版本,或者將父模組和子模組中的"version"改為"revision"。
  8. 修改web.xml:

  9. 在web.xml中,idea會自動為我們配置dispatcher的初始化引數:contextConfigLocation, 其值為:/WEB-INF/applicationContext.xml,接下來會對其進行配置
  10. 配置applicationContext.xml:

  11. <?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:context="http://www.springframework.org/schema/context"
                   xmlns:mvc="http://www.springframework.org/schema/mvc"
                   xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/mvc
           https://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <!--自動掃描spring註解的元件,避免臃腫的bean配置-->
                <!--註解元件包括:@Component, @Repository, @Service, @Controller, @RestController, @ControllerAdvice, @Configuration-->
                <!--base-package:包含有註解元件的包名-->
        <context:component-scan base-package="com.zx.demo"/>
                <!--註解驅動,spring mvc專屬配置,主要註冊了dispatcher所需的RequestMappingHandlerMapping和RequestMappingHandlerAdapter-->
        <mvc:annotation-driven/>
    </beans>
  12. 建立Controller:

  13. import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    //@Controller配置宣告的元件會被Spring自動裝配
    @Controller
    public class TestController {
        //@RequestMapping註解對應:RequestMappingHandlerMapping
        @RequestMapping("/hello")
        //@ResponseBody註解表示可以直接向前端返回java物件
        @ResponseBody
        public String test() {
            //返回字串
            return "Hello world.";
        }
    }
  14. 部署到tomcat並執行,瀏覽器中進行驗證: