Spring入門(二):SpringBoot之基礎Web開發

上回

現在,我們已經能自行完成SpringBoot的初級項目搭建了,接下來看如何實現一些Web開發中的基礎功能。

先看項目完整的目錄結構:

1. 返回Json數據

創建model文件夾,並新建Person類,程式碼如下:

package com.example.hellospringboot.model;

public class Person {

    private int id = 0;

    private String name = "";

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

在controller文件夾下創建JsonController,程式碼如下:

package com.example.hellospringboot.controller;

import com.example.hellospringboot.model.Person;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/json")
public class JsonController {

    @GetMapping("/person")
    public Person person(){
        Person person = new Person();
        person.setId(1);
        person.setName("祖斯特");
        return person;
    }
}

@RestController註解我們在上一節已經用過了,代表整個Controller請求方法僅返回純數據,不包含Html頁面資訊

這種情況多見於前後端分離的情況,前端框架(如Vue)在拿到後端返回數據之後自行組織頁面渲染

重啟程式,訪問地址 //localhost:8080/json/person ,頁面顯示如下:

{"id":1,"name":"祖斯特"}

說明程式碼執行正確

2. 返回Html頁面

接下來我們看如何返回完整的Html渲染頁面

要實現這個功能,需要引入前端模板引擎,官方推薦Thymeleaf

我們在pom中加入其依賴配置:

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- 引入thymeleaf依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

在controller文件夾下創建HtmlController類:

package com.example.hellospringboot.controller;

import com.example.hellospringboot.model.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/html")
public class HtmlController {

    @GetMapping("/person")
    public ModelAndView person(){
        ModelAndView mv = new ModelAndView();
        Person person = new Person();
        person.setId(1);
        person.setName("祖斯特");
        mv.addObject("person", person);
        mv.setViewName("person");
        return mv;
    }
}

跟返回Json數據不同,HtmlController註解為@Controller,方法需要返回一個ModelAndView對象

mv.addObject 代表我們向前端Html模板提供綁定數據

mv.setViewName 代表我們要設定的Html模板,這裡指定名稱為:person

接下來我們在 resources/templates 路徑下創建Thymeleaf模板文件 person.html

<!DOCTYPE html>
<html lang="en" xmlns:th="//www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Person測試頁面</title>
</head>
<body>
    <div>編號:<span th:text="${person.getId()}">默認編號</span></div>
    <div>姓名:<span th:text="${person.getName()}">默認名字</span></div>

</body>
</html>

Thymeleaf擁有優秀的設計理念,所有的模板文件即使沒有後端程式也可以獨立渲染(th標籤不會引發異常),以供前端設計師查看效果

而 th:text=”${xxx}” 代表程式執行時,標籤的內容將動態替換為後端傳過來的數據內容

重啟程式,訪問地址 //localhost:8080/html/person ,頁面顯示如下:

編號:1
姓名:祖斯特

3. 靜態資源訪問

我們一般將靜態文件(js、css、圖片等)存放在單獨的文件夾下,SpringBoot默認地址為 resources/static
但是為了使其能夠正常訪問,我們扔需要在application.properties中加入如下配置:
# 應用名稱
spring.application.name=hellospringboot
# 應用服務 WEB 訪問埠
server.port=8080

# 使用static作為靜態資源根路徑,且不需要其他路徑前綴
spring.mvc.static-path-pattern=/**
spring.web.resources.static-locations=classpath:/static/

之後我們在static下放入一張圖片head.png測試效果

person.html 加個<img>標籤驗證下效果:

<!DOCTYPE html>
<html lang="en" xmlns:th="//www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Person測試頁面</title>
</head>
<body>
    <div>編號:<span th:text="${person.getId()}">默認編號</span></div>
    <div>姓名:<span th:text="${person.getName()}">默認名字</span></div>
    <div>
        <img src="/head.png">
    </div>
</body>
</html>

路徑 src=/head.png 代表是static根路徑

如果直接寫 src=head.png 則為相對路徑:static/html/head.png

需要注意這一點,大家可以自行嘗試

訪問地址 //localhost:8080/html/person,頁面顯示效果如下:

 

 4. 自定義錯誤頁面

如果我們訪問一個不存在的地址://localhost:8080/notexist,會彈出如下的錯誤頁面:

 

 SpringBoot已經為大家提供了自定義錯誤頁面的方法,實現起來非常簡單

 我們在 resources/static 下創建文件夾 error,在error下創建 404.html 即可

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>頁面不存在</title>
</head>
<body>
頁面不存在!
</body>
</html>

重新啟動程式,訪問 //localhost:8080/notexist ,效果如下:

頁面不存在! 

你可能感到困惑,這樣豈不是要一個錯誤創建一個html文件?!

SpringBoot為我們提供了通配符支援,比如:4xx.html 可以代表401、402、403、404等所有400+的錯誤

以上。

 

關於 SpringBoot之基礎Web開發 我們就介紹到這,下一節我們看如何實現SpringBoot和mysql資料庫之間的交互,敬請期待。