🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 使用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开发了一个网页。