# 使用Spring MVC服務Web內容
本指南將引導您完成使用Spring創建“ Hello,World”網站的過程。
## 你會建立什么
您將構建一個具有靜態主頁的應用程序,該應用程序還將在以下位置接受HTTP GET請求: `[http://localhost:8080/greeting](http://localhost:8080/greeting)`.
它將以顯示HTML的網頁作為響應。 HTML的正文將包含問候語:“ Hello,World!”
您可以使用可選的自定義問候語 `name`查詢字符串中的參數。 該網址可能是 `[http://localhost:8080/greeting?name=User](http://localhost:8080/greeting?name=User)`.
這 `name` 參數值會覆蓋默認值 `World` 并通過將內容更改為“您好,用戶!”反映在響應中
## 你需要什么
* 約15分鐘
* 最喜歡的文本編輯器或IDE
* [JDK 1.8](http://www.oracle.com/technetwork/java/javase/downloads/index.html) 或更高版本
* [Gradle 4+](http://www.gradle.org/downloads) 或 [Maven 3.2+](https://maven.apache.org/download.cgi)
* 您還可以將代碼直接導入到IDE中:
* [彈簧工具套件(STS)](https://spring.io/guides/gs/sts)
* [IntelliJ IDEA](https://spring.io/guides/gs/intellij-idea/)
## 如何完成本指南
像大多數Spring 一樣 [入門指南](https://spring.io/guides) ,您可以從頭開始并完成每個步驟,也可以繞過您已經熟悉的基本設置步驟。 無論哪種方式,您最終都可以使用代碼。
要 **從頭開始** ,請繼續進行“ [從Spring Initializr開始”](https://spring.io/guides/gs/serving-web-content/#scratch) 。
要 **跳過基礎知識** ,請執行以下操作:
* [下載](https://github.com/spring-guides/gs-serving-web-content/archive/master.zip) 并解壓縮本指南的源存儲庫,或使用 對其進行克隆 [Git](https://spring.io/understanding/Git) : `git clone [https://github.com/spring-guides/gs-serving-web-content.git](https://github.com/spring-guides/gs-serving-web-content.git)`
* 光盤進入 `gs-serving-web-content/initial`
* 繼續 [創建Web控制器](https://spring.io/guides/gs/serving-web-content/#initial) 。
**完成后** ,您可以根據中的代碼檢查結果 `gs-serving-web-content/complete`.
## 從Spring Initializr開始
如果您使用Maven,請訪問 [Spring Initializr](https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=serving-web-content&name=serving-web-content&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.serving-web-content&dependencies=web,thymeleaf,devtools) 以生成具有所需依賴項(Spring Web,Thymeleaf和Spring Boot DevTools)的新項目。
以下清單顯示了 `pom.xml` 選擇Maven時創建的文件:
~~~
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>serving-web-content</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>serving-web-content</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
~~~
如果您使用Gradle,請訪問 [Spring Initializr](https://start.spring.io/#!type=gradle-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=serving-web-content&name=serving-web-content&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.serving-web-content&dependencies=web,thymeleaf,devtools) 以生成具有所需依賴項(Spring Web,Thymeleaf和Spring Boot DevTools)的新項目。
以下清單顯示了 `build.gradle` 選擇Gradle時創建的文件:
~~~
plugins {
id 'org.springframework.boot' version '2.4.3'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
~~~
### 手動初始化(可選)
如果要手動初始化項目而不是使用前面顯示的鏈接,請按照以下步驟操作:
1. 導航到 [https://start.spring.io](https://start.spring.io) 。 該服務提取應用程序所需的所有依賴關系,并為您完成大部分設置。
2. 選擇Gradle或Maven以及您要使用的語言。 本指南假定您選擇了Java。
3. 單擊 **Dependencies,** 然后選擇 **Spring Web** , **Thymeleaf** 和 **Spring Boot DevTools** 。
4. 點擊 **生成** 。
5. 下載生成的ZIP文件,該文件是使用您的選擇配置的Web應用程序的存檔。
如果您的IDE集成了Spring Initializr,則可以從IDE中完成此過程。
## 創建一個Web控制器
在Spring建立網站的方法中,HTTP請求由控制器處理。 您可以通過 [`@Controller`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/Controller.html)注解。 在以下示例中, `GreetingController` 處理GET請求 `/greeting` 通過返回一個名稱 [`View`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/View.html) (在這種情況下, `greeting`)。 一個 `View`負責呈現HTML內容。 以下清單(來自 `src/main/java/com/example/servingwebcontent/GreetingController.java`)顯示控制器:
~~~
package com.example.servingwebcontent;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class GreetingController {
@GetMapping("/greeting")
public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "greeting";
}
}
~~~
該控制器簡潔明了,但是有很多事情要做。 我們將其逐步分解。
這 `@GetMapping` 注釋可確保HTTP GET請求 `/greeting` 映射到 `greeting()` 方法。
[`@RequestParam`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html) 綁定查詢字符串參數的值 `name` 進入 `name` 的參數 `greeting()`方法。 此查詢字符串參數不是 `required`。 如果請求中不存在,則 `defaultValue` 的 `World`用來。 的價值 `name` 參數已添加到 [`Model`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/ui/Model.html) 對象,最終使視圖模板可以訪問它。
方法主體的實現依賴于視圖技術(在本例中為 [Thymeleaf](http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html) )執行HTML的服務器端呈現。 Thymeleaf解析 `greeting.html` 模板并評估 `th:text` 表示值的表達式 `${name}` 在控制器中設置的參數。 `src/main/resources/templates/greeting.html`)顯示 `greeting.html` 模板:
~~~
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>
~~~
確保您的類路徑上有Thymeleaf(工件坐標: org.springframework.boot:spring-boot-starter-thymeleaf)。 Github中的“初始”和“完整”樣本中已經存在該文件。
## Spring Boot開發工具
開發Web應用程序的常見功能是對更改進行編碼,重新啟動應用程序以及刷新瀏覽器以查看更改。 這整個過程可能會花費大量時間。 為了加快刷新周期,Spring Boot提供了一個方便的模塊,稱為 [spring-boot-devtools](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-devtools) 。 Spring Boot Devtools:
* 啟用 [熱插拔](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-hotswapping) 。
* 切換模板引擎以禁用緩存。
* 使LiveReload能夠自動刷新瀏覽器。
* 其他合理的默認設置基于開發而不是生產。
## 運行應用程序
Spring Initializr為您創建一個應用程序類。 在這種情況下,您無需進一步修改Spring Initializr提供的類。 以下清單(來自 `src/main/java/com/example/servingwebcontent/ServingWebContentApplication.java`)顯示了應用程序類:
~~~
package com.example.servingwebcontent;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ServingWebContentApplication {
public static void main(String[] args) {
SpringApplication.run(ServingWebContentApplication.class, args);
}
}
~~~
`@SpringBootApplication` 是一個方便注釋,它添加了以下所有內容:
* `@Configuration`:將類標記為應用程序上下文的Bean定義的源。
* `@EnableAutoConfiguration`:告訴Spring Boot根據類路徑設置,其他bean和各種屬性設置開始添加bean。 例如,如果 `spring-webmvc` 在類路徑上,此注釋將應用程序標記為Web應用程序并激活關鍵行為,例如設置 `DispatcherServlet`.
* `@ComponentScan`:告訴Spring在服務器中尋找其他組件,配置和服務 `com/example` 包,讓它找到控制器。
這 `main()` 方法使用Spring Boot的 `SpringApplication.run()`啟動應用程序的方法。 您是否注意到沒有一行XML? 沒有 `web.xml`文件。 該Web應用程序是100%純Java,因此您無需處理任何管道或基礎結構。
### 建立可執行的JAR
您可以使用Gradle或Maven從命令行運行該應用程序。 您還可以構建一個包含所有必需的依賴項,類和資源的可執行JAR文件,然后運行該文件。 生成可執行jar使得在整個開發生命周期中,跨不同環境等等的情況下,都可以輕松地將服務作為應用程序進行發布,版本控制和部署。
如果您使用Gradle,則可以通過使用以下命令運行該應用程序 `./gradlew bootRun`。 或者,您可以通過使用以下命令構建JAR文件: `./gradlew build` 然后運行JAR文件,如下所示:
~~~
java -jar build/libs/gs-serving-web-content-0.1.0.jar
~~~
如果您使用Maven,則可以通過使用以下命令運行該應用程序 `./mvnw spring-boot:run`。 或者,您可以使用以下命令構建JAR文件: `./mvnw clean package` 然后運行JAR文件,如下所示:
~~~
java -jar target/gs-serving-web-content-0.1.0.jar
~~~
此處描述的步驟將創建可運行的JAR。 您還可以 構建經典的WAR文件 。
顯示日志記錄輸出。 該應用程序應在幾秒鐘內啟動并運行。
## 測試應用
現在該網站正在運行,請訪問 `[http://localhost:8080/greeting](http://localhost:8080/greeting)`,您應該會在這里看到“你好,世界!”
提供一個 `name` 通過訪問查詢字符串參數 `[http://localhost:8080/greeting?name=User](http://localhost:8080/greeting?name=User)`。 注意消息從“ Hello,World!”的變化。 改為“您好,用戶!”:
此更改表明 [`@RequestParam`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html) 安排在 `GreetingController`正在按預期工作。 這 `name` 參數已賦予默認值 `World`,但可以通過查詢字符串顯式覆蓋它。
## 添加主頁
可以從Spring Boot應用程序中獲取包括HTML,JavaScript和CSS在內的靜態資源,方法是將其放置在源代碼中的正確位置。 默認情況下,Spring Boot從類路徑中的資源提供靜態內容 `/static` (或者 `/public`)。 這 `index.html` 資源是特殊的,因為它(如果存在)用作“歡迎頁面”, `"serving-web-content/ which means it is served up as the root resource (that is, at `http://localhost:8080/`)。 因此,您需要創建以下文件(可以在以下文件中找到 `src/main/resources/static/index.html`):
~~~
<!DOCTYPE HTML>
<html>
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Get your greeting <a href="/greeting">here</a></p>
</body>
</html>
~~~
重新啟動應用程序時,您會在以下位置看到HTML: `[http://localhost:8080/](http://localhost:8080/)`.
## 概括
恭喜你! 您剛剛使用Spring開發了一個網頁。
- springboot概述
- springboot構建restful服務
- spring構建一個RESTful Web服務
- spring定時任務
- 消費RESTful Web服務
- gradle構建項目
- maven構建項目
- springboot使用jdbc
- springboot應用上傳文件
- 使用LDNA驗證用戶
- 使用 spring data redis
- 使用 spring RabbitTemplate消息隊列
- 用no4j訪問nosql數據庫
- springboot驗證web表單
- Spring Boot Actuator構j建服務
- 使用jms傳遞消息
- springboot創建批處理服務
- spring security保護web 安全
- 在Pivotal GemFire中訪問數據
- 使用Spring Integration
- 使用springboot jpa進行數據庫操作
- 數據庫事務操作
- 操作mongodb
- springmvc+tymleaf創建web應用
- 將Spring Boot JAR應用程序轉換為WAR
- 創建異步服務
- spring提交表單
- 使用WebSocket構建交互式Web應用程序
- 使用REST訪問Neo4j數據
- jquery消費restful
- springboot跨域請求
- 消費SOAP Web服務
- springboot使用緩存
- 使用Vaadin創建CRUD UI
- 使用REST訪問JPA數據
- 使用REST訪問Pivotal GemFire中的數據
- 構建soap服務
- 使用rest訪問mongodb數據
- 構建springboot應用docker鏡像
- 從STS部署到Cloud Foundry
- springboot測試web應用
- springboot訪問mysql
- springboot編寫自定義模塊并使用
- 使用Google Cloud Pub / Sub進行消息傳遞
- 構建反應式RESTful Web服務
- 使用Redis主動訪問數據
- Spring Boot 部署到Kubernetes
- 使用反應式協議R2DBC訪問數據
- Spring Security架構
- spring構建Docker鏡像詳解
- Spring Boot和OAuth2
- springboot應用部署到k8s
- spring構建rest服務詳解