1. 程式人生 > 其它 >【SpringMVC 從 0 開始】動手實現世界著名程式

【SpringMVC 從 0 開始】動手實現世界著名程式

一、什麼是 MVC

MVC 其實是一種架構思想,將軟體按照模型、檢視、控制器來劃分。

  • M:是指 Model,就是模型層,指工程中的 JavaBean,作用是處理資料。
  • V:是指 View,檢視層,指工程中的 html 或 jsp 等頁面,作用是與使用者進行互動,展示資料。
  • C:是指 Controller,控制層,指工程中的 servlet,作用是接收請求和響應瀏覽器。

關於 M 中的 javabean,可以分為兩類:

  • 實體類Bean:專門儲存業務資料的,如 Student、User 等。
  • 業務處理 Bean:指 Service 或 Dao 物件,專門用於處理業務邏輯和資料訪問。

MVC 工作流程

  1. 使用者通過檢視層傳送請求到伺服器
  2. 在伺服器中請求被 Controller 接收
  3. Controller 呼叫相應的Model層處理請求
  4. 處理完畢將結果返回到 Controller
  5. Controller再根據請求處理的結果找到相應的View檢視,渲染資料後最終響應給瀏覽器

二、什麼是 SpringMVC

SpringMVC 是 Spring 的一個後續產品,是 Spring 的一個子專案,SpringMVC 是 Spring 為表述層開發提供的一整套完備的解決方案。

目前業界普遍選擇了 SpringMVC 作為 Java EE 專案表述層開發的首選方案

SpringMVC 的特點

  • Spring 家族原生產品
    ,與 IOC 容器等基礎設施無縫對接
  • 基於原生的 Servlet,通過了功能強大的前端控制器 DispatcherServlet,對請求和響應進行統一處理
  • 表述層各細分領域需要解決的問題全方位覆蓋,提供全面解決方案
  • 程式碼清新簡潔,大幅度提升開發效率
  • 內部元件化程度高,可插拔式元件即插即用,想要什麼功能配置相應元件即可
  • 效能卓著,尤其適合現代大型、超大型網際網路專案要求

三、開發環境準備

在實現世界著名程式之前需要準備好開發環境。

  • IDE:idea 2018.3
  • 構建工具:maven3.5.4
  • 伺服器:tomcat8
  • Spring版本:5.3.1

四、動手實現 Hello world

一起動動手。

1. 建立工程

這裡新建一個 project,我這取名叫 springmvc。然後在裡面新建一個 module,叫 springmvc-demo1,最終完成下來。

注意,新增 web模組,是在 File-Project structure 裡。

2. 引入依賴

在模組 springmvc-demo1 下面的 pom.xml 檔案裡,需要引入相關依賴。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springmvc</artifactId>
        <groupId>com.pingguo.mvc</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springmvc-demo1</artifactId>
    <!--打包方式-->
    <packaging>war</packaging>

    <dependencies>
        <!-- SpringMVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.1</version>
        </dependency>

        <!-- 日誌 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>

        <!-- ServletAPI -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- Spring5和Thymeleaf整合包 -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.12.RELEASE</version>
        </dependency>
    </dependencies>

</project>

3. 配置 web.xml

在 webapp 下的 web.xml 中如下配置:

<?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_4_0.xsd"
         version="4.0">

    <!-- 配置SpringMVC的前端控制器,對瀏覽器傳送的請求統一進行處理 -->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 通過初始化引數指定SpringMVC配置檔案的位置和名稱 -->
        <init-param>
            <!-- contextConfigLocation為固定值 -->
            <param-name>contextConfigLocation</param-name>
            <!-- 使用classpath:表示從類路徑查詢配置檔案,例如maven工程中的src/main/resources -->
            <param-value>classpath:springMVC.xml</param-value>
        </init-param>
        <!--
             作為框架的核心元件,在啟動過程中有大量的初始化操作要做
            而這些操作放在第一次請求時才執行會嚴重影響訪問速度
            因此需要通過此標籤將啟動控制DispatcherServlet的初始化時間提前到伺服器啟動時
        -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <!--
            設定springMVC的核心控制器所能處理的請求的請求路徑
            /所匹配的請求可以是/login或.html或.js或.css方式的請求路徑
            但是/不能匹配.jsp請求路徑的請求
        -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

3. 配置 spring 配置檔案

在 resources 下新建 配置檔案。

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 自動掃描包 -->
    <context:component-scan base-package="com.pingguo.mvc.controller"></context:component-scan>

    <!-- 配置Thymeleaf檢視解析器 -->
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">

                        <!-- 檢視字首 -->
                        <property name="prefix" value="/WEB-INF/templates/"/>

                        <!-- 檢視字尾 -->
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8" />
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
</beans>

這裡檢視層使用 Thymeleaf,先不著急前後端分離,學習要一步步地來。

4. 編寫請求控制器

由於前端控制器對瀏覽器傳送的請求進行了統一的處理,但是具體的請求有不同的處理過程,因此需要建立處理具體請求的類,即請求控制器。

請求控制器中每一個處理請求的方法成為控制器方法。

因為SpringMVC的控制器由一個POJO(普通的Java類)擔任,因此需要通過 @Controller 註解將其標識為一個控制層元件,交給 Spring 的 IoC容器管理,此時 SpringMVC 才能夠識別控制器的存在。

package com.pingguo.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {
    // @RequestMapping註解:處理請求和控制器方法之間的對映關係
    // @RequestMapping註解的value屬性可以通過請求地址匹配請求,/表示的當前工程的上下文路徑
    @RequestMapping(value = "/")
    public String index() {
        // 返回檢視名稱
        return "index";
    }

    @RequestMapping("/target")
    public String toTarget() {
        return "target";
    }
}

這裡我直接加了 2 個方法,對應兩個頁面。

5. 編寫頁面檔案

在 webapp/WEB-INF/templates 下,編寫 html 檔案。

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首頁</title>
</head>
<body>
<h1>Hello World</h1>
<a th:href="@{/target}">訪問目標頁面 target.html </a>
</body>
</html>

這裡加了一個<a>標籤,用來跳轉到另一個頁面 target.html。裡面的th:href="@{/target}用的是 thymeleaf 裡的語法,不用太過糾結與此,這不是本次學習的重點。因為後面最終還是會用前後端分離的方式進行應用的開發。

target.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>target</title>
</head>
<body>
<h1>target</h1>
</body>
</html>

6. 啟動專案

因為專案打包方式是 war 包,部署在 tomcat 裡,所以要先在本地安裝個 tomcat,教程網上一大把。

然後,在idea 中 add run configuration。

先是 Deployment。

這裡的 Application context 就是應用上下文了,比如我要訪問 /target,實際專案啟動後在瀏覽器中訪問的是:http://localhost:8080/springmvc/target

接下來,就是 Server 配置了。

啟動,可以run 也可以 debug,debug 下可以用來斷點除錯。

啟動之後,預設會開啟 http://localhost:8080/springmvc/

點選 index 頁的 跳轉連線,成功跳轉到 target 頁。

再回顧下請求頁面的過程:

  • 瀏覽器傳送請求,若請求地址符合前端控制器的 url-pattern,該請求就會被前端控制器DispatcherServlet處理。
  • 前端控制器會讀取 SpringMVC 的核心配置檔案,通過掃描元件找到控制器,將請求地址和控制器中 @RequestMapping 註解的 value 屬性值進行匹配,若匹配成功,該註解所標識的控制器方法就是處理請求的方法。
  • 處理請求的方法需要返回一個字串型別的檢視名稱,該檢視名稱會被檢視解析器解析,加上字首和字尾組成檢視的路徑,通過 Thymeleaf 對檢視進行渲染,最終轉發到檢視所對應頁面。

感謝《尚矽谷》的學習資源。

--不要用肉體的勤奮,去掩蓋思考的懶惰--