开篇词
该指南将引导你使用 Spring 创建 “Hello, World” 网站。
你将创建的应用
我们将创建一个具有静态主页的应用,该应用还将在以下地址接受 HTTP GET 请求:http://localhost:8080/greeting。
它将以显示 HTML 的网页作为响应。HTML 的正文将包含问候语:“Hello World!”
我们可以在查询字符串中使用可选的 name
参数来自定义问候语。然后,URL 可能是 http://localhost:8080/greeting?name=User。
name
参数值将覆盖 World
的默认值,并且在内容中更改为 “Hello, User!” 会反映在响应中。
你将需要的工具
- 大概 15 分钟左右;
- 你最喜欢的文本编辑器或集成开发环境(IDE)
- JDK 1.8 或更高版本;
- Gradle 4+ 或 Maven 3.2+
- 你还可以将代码直接导入到 IDE 中:
如何完成这个指南
像大多数的 Spring 入门指南一样,你可以从头开始并完成每个步骤,也可以绕过你已经熟悉的基本设置步骤。如论哪种方式,你最终都有可以工作的代码。
- 要从头开始,移步至从 Spring Initializr 开始;
- 要跳过基础,执行以下操作:
- 下载并解压缩该指南将用到的源代码,或借助 Git 来对其进行克隆操作:
git clone https://github.com/spring-guides/gs-serving-web-content.git
- 切换至
gs-serving-web-content/initial
目录; - 跳转至该指南的创建 Web 控制器。
- 下载并解压缩该指南将用到的源代码,或借助 Git 来对其进行克隆操作:
待一切就绪后,可以检查一下 gs-serving-web-content/complete
目录中的代码。
从 Spring Initializr 开始
对于所有的 Spring 应用来说,你应该从 Spring Initializr 开始。Initializr 提供了一种快速的方法来提取应用程序所需的依赖,并为你完成许多设置。该示例需要 Spring Web、Thymeleaf 以及 Spring Boot DevTools 依赖。下图显示了此示例项目的 Initializr 设置:
上图显示了选择 Maven 作为构建工具的 Initializr。你也可以使用 Gradle。它还将
com.example
和serving-web-content
的值分别显示为 Group 和 Artifact。在本示例的其余部分,将用到这些值。
以下清单显示了选择 Maven 时创建的 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 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.2.2.RELEASE</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
以下清单显示了在选择 Gradle 时创建的 build.gradle
文件:
plugins {
id 'org.springframework.boot' version '2.2.2.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
configurations {
developmentOnly
runtimeClasspath {
extendsFrom developmentOnly
}
}
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') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
创建 Web 控制器
在 Spring 建立网站的方法中,HTTP 请求由控制器处理。我们可以通过 @Controller
注解来轻松识别控制器。在下面的实例中,GreetingController
通过返回 View
的名称(在该示例中为 greeting
)来处理 /greeting
的 GET
请求。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
注解确保将 /greeting
的 HTTP GET 请求映射到 greeting()
方法。
@RequestParam
将查询字符串参数 name
的值绑定到 greeting()
方法的 name
参数中。不 required
该查询字符串参数。如果请求中不存在,则使用 defaultValue
的 World
。name
参数的值将添加到 Model
对象,最终使视图模版可以访问它。
方法主体的实现依赖于视图技术(在该示例中为 Thymeleaf)执行 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 Devtools
开发 Web 应用的常见功能是对做代码变更,重新启动应用以及刷新浏览器以查看更改。整个过程可能会花费大量时间。为了加快刷新周期,Spirng Boot 提供了一个方便的模块,称为 spring-boot-devtools。Spring Boot Devtools:
- 启用热插拔;
- 切换模版引擎以禁用缓存;
- 激活 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。@ComponentScan
:告知 Spring 在com/example
包中寻找他组件、配置以及服务。
main()
方法使用 Spring Boot 的 SpringApplication.run()
方法启动应用。
构建可执行 JAR
我们可以结合 Gradle 或 Maven 来从命令行运行该应用。我们还可以构建一个包含所有必须依赖项、类以及资源的可执行 JAR 文件,然后运行该文件。在整个开发生命周期中,跨环境等等情况下,构建可执行 JAR 可以轻松地将服务作为应用进行发布、版本化以及部署。
如果使用 Gradle,则可以借助 ./gradlew bootRun
来运行应用。或通过借助 ./gradlew build
来构建 JAR 文件,然后运行 JAR 文件,如下所示:
java -jar build/libs/gs-serving-web-content-0.1.0.jar
由官网提供的以上这条命令的执行结果与我本地的不一样,我需要这样才能运行:
java -jar build/libs/serving-web-content-0.0.1-SNAPSHOT.jar
。
如果使用 Maven,则可以借助 ./mvnw spring-boot:run
来运行该用。或可以借助 ./mvnw clean package
来构建 JAR 文件,然后运行 JAR 文件,如下所示:
java -jar target/gs-serving-web-content-0.1.0.jar
由官网提供的以上这条命令的执行结果与我本地的不一样,我需要这样才能运行:
java -jar target/serving-web-content-0.0.1-SNAPSHOT.jar
。
我们还可以构建一个经典的 WAR 文件。
显示日志记录输出。该应用应在几秒内启动并运行。
测试应用
现在,该网站正在运行,请访问 http://localhost:8080/greeting,我们将在其中看到 “Hello World!”。
通过访问 http://localhost:8080/greeting?name=User 提供 name
查询字符串参数。注意消息如何从 “Hello, World!” 变为 “Hello, User!”:
该更改说明 GreetingController
中的 @RequestParam
布局按预期工作了。name
参数的默认值是 World
,但是可以通过查询字符串显式覆盖它。
添加主页
可以从 Spring Boot 应用中获取包括 HTML、JavaScript 以及 CSS 在内的静态资源,方法是将其放置在源代码中的正确位置。默认情况下,Spring Boot 从 /static
(或 /public
)的类路径中资源提供的静态内容。index.html
资源是特殊的,因为它(如果存在)将用作 “欢迎页面”,这意味着它将用作根资源(即位于 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>
重新启动应用时,我们将在 http://localhost:8080/
上看到 HTML。
概述
恭喜你!我们刚刚使用 Spring 开发了一个网页。
参见
以下指南也可能会有所帮助:
- 使用 Spring Boot 构建应用(尽请期待~)
- 使用 GemFire 访问数据
- 使用JPA访问数据
- 使用 MongoDB 访问数据
- 使用 MySQL 访问数据(尽请期待~)
- 测试 Web 层(尽请期待~)
- 构建 RESTful Web 服务
想看指南的其他内容?请访问该指南的所属专栏:《Spring 官方指南》