Serving Web Content with Spring MVC

This guide walks you through the process of creating a “Hello, World” web site with Spring.
What You Will Build

You will build an application that has a static home page and that will also accept HTTP GET requests at: http://localhost:8080/greeting.

It will respond with a web page that displays HTML. The body of the HTML will contain a greeting: “Hello, World!”

You can customize the greeting with an optional name parameter in the query string. The URL might then be http://localhost:8080/greeting?name=User.

The name parameter value overrides the default value of World and is reflected in the response by the content changing to “Hello, User!”
What You Need

About 15 minutes

A favorite text editor or IDE

JDK 1.8 or later

Gradle 4+ or Maven 3.2+

You can also import the code straight into your IDE:

    Spring Tool Suite (STS)

    IntelliJ IDEA

How to complete this guide

Like most Spring Getting Started guides, you can start from scratch and complete each step or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.

To start from scratch, move on to Starting with Spring Initializr.

To skip the basics, do the following:

Download and unzip the source repository for this guide, or clone it using Git: git clone https://github.com/spring-guides/gs-serving-web-content.git

cd into gs-serving-web-content/initial

Jump ahead to Create a Web Controller.

When you finish, you can check your results against the code in gs-serving-web-content/complete.
Starting with Spring Initializr

For all Spring applications, you should start with the Spring Initializr. The Initializr offers a fast way to pull in all the dependencies you need for an application and does a lot of the setup for you. This example needs the Spring Web, Thymeleaf, and Spring Boot DevTools dependencies. The following image shows the Initializr set up for this sample project:
initializr
The preceding image shows the Initializr with Maven chosen as the build tool. You can also use Gradle. It also shows values of com.example and serving-web-content as the Group and Artifact, respectively. You will use those values throughout the rest of this sample.

The following listing shows the pom.xml file that is created when you choose Maven:

<?xml version="1.0" encoding="UTF-8"?>


4.0.0

org.springframework.boot
spring-boot-starter-parent
2.2.2.RELEASE


com.example
serving-web-content
0.0.1-SNAPSHOT
serving-web-content
Demo project for Spring Boot

<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>

The following listing shows the build.gradle file that is created when you choose 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()
}

Create a Web Controller

In Spring’s approach to building web sites, HTTP requests are handled by a controller. You can easily identify the controller by the @Controller annotation. In the following example, GreetingController handles GET requests for /greeting by returning the name of a View (in this case, greeting). A View is responsible for rendering the HTML content. The following listing (from src/main/java/com/example/servingwebcontent/GreetingController.java) shows the controller:

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";
}

}

This controller is concise and simple, but there is plenty going on. We break it down step by step.

The @GetMapping annotation ensures that HTTP GET requests to /greeting are mapped to the greeting() method.

@RequestParam binds the value of the query string parameter name into the name parameter of the greeting() method. This query string parameter is not required. If it is absent in the request, the defaultValue of World is used. The value of the name parameter is added to a Model object, ultimately making it accessible to the view template.

The implementation of the method body relies on a view technology (in this case, Thymeleaf) to perform server-side rendering of the HTML. Thymeleaf parses the greeting.html template and evaluates the th:text expression to render the value of the ${name} parameter that was set in the controller.The following listing (from src/main/resources/templates/greeting.html) shows the greeting.html template:

Getting Started: Serving Web Content

Make sure you have Thymeleaf on your classpath (artifact co-ordinates: org.springframework.boot:spring-boot-starter-thymeleaf). It is already there in the "initial" and "complete" samples in Github.

Spring Boot Devtools

A common feature of developing web applications is coding a change, restarting your application, and refreshing the browser to view the change. This entire process can eat up a lot of time. To speed up this refresh cycle, Spring Boot offers with a handy module known as spring-boot-devtools. Spring Boot Devtools:

Enables hot swapping.

Switches template engines to disable caching.

Enables LiveReload to automatically refresh the browser.

Other reasonable defaults based on development instead of production.

Run the Application

The Spring Initializr creates an application class for you. In this case, you need not further modify the class provided by the Spring Initializr. The following listing (from src/main/java/com/example/servingwebcontent/ServingWebContentApplication.java) shows the application class:

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 is a convenience annotation that adds all of the following:

@Configuration: Tags the class as a source of bean definitions for the application context.

@EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. For example, if spring-webmvc is on the classpath, this annotation flags the application as a web application and activates key behaviors, such as setting up a DispatcherServlet.

@ComponentScan: Tells Spring to look for other components, configurations, and services in the com/example package, letting it find the controllers.

The main() method uses Spring Boot’s SpringApplication.run() method to launch an application. Did you notice that there was not a single line of XML? There is no web.xml file, either. This web application is 100% pure Java and you did not have to deal with configuring any plumbing or infrastructure.
Build an executable JAR

You can run the application from the command line with Gradle or Maven. You can also build a single executable JAR file that contains all the necessary dependencies, classes, and resources and run that. Building an executable jar so makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.

If you use Gradle, you can run the application by using ./gradlew bootRun. Alternatively, you can build the JAR file by using ./gradlew build and then run the JAR file, as follows:

java -jar build/libs/gs-serving-web-content-0.1.0.jar

If you use Maven, you can run the application by using ./mvnw spring-boot:run. Alternatively, you can build the JAR file with ./mvnw clean package and then run the JAR file, as follows:

java -jar target/gs-serving-web-content-0.1.0.jar

The steps described here create a runnable JAR. You can also build a classic WAR file.

Logging output is displayed. The application should be up and running within a few seconds.
Test the Application

Now that the web site is running, visit http://localhost:8080/greeting, where you should see “Hello, World!”

Provide a name query string parameter by visiting http://localhost:8080/greeting?name=User. Notice how the message changes from “Hello, World!” to “Hello, User!”:

This change demonstrates that the @RequestParam arrangement in GreetingController is working as expected. The name parameter has been given a default value of World, but it can be explicitly overridden through the query string.
Add a Home Page

Static resources, including HTML and JavaScript and CSS, can be served from your Spring Boot application by dropping them into the right place in the source code. By default, Spring Boot serves static content from resources in the classpath at /static (or /public). The index.html resource is special because, if it exists, it is used as a "welcome page,"serving-web-content/ which means it is served up as the root resource (that is, athttp://localhost:8080/). As a result, you need to create the following file (which you can find in src/main/resources/static/index.html):

Getting Started: Serving Web Content

Get your greeting here

When you restart the application, you will see the HTML at http://localhost:8080/.
Summary

Congratulations! You have just developed a web page by using Spring.

translate:
翻译:

本指南将引导您完成使用Spring创建“Hello,World”网站的过程。

你将建造什么
您将构建一个具有静态主页的应用程序,该应用程序还将接受HTTP://localhost:8080/greeting上的HTTP GET请求。
它将用一个显示HTML的网页来响应。HTML的主体将包含一个问候语:“你好,世界!”
可以使用查询字符串中的可选名称参数自定义问候语。URL可能是http://localhost:8080/greeting?name=用户。
name参数值覆盖World的默认值,内容更改为“Hello,User!”!”
你需要什么
大约15分钟
最喜欢的文本编辑器或IDE
JDK 1.8或更高版本
Gradle 4+或Maven 3.2+
您还可以直接将代码导入到IDE中:
Spring工具套件(STS)
智力观念
如何完成本指南
与大多数Spring入门指南一样,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。不管怎样,你最终都会使用代码。
要从头开始,请继续使用Spring初始化器。
要跳过基本步骤,请执行以下操作:
下载并解压缩此指南的源存储库,或使用Git克隆它:Git clone https://github.com/spring-guides/gs-serving-web-content.Git
cd到gs服务web内容/初始
跳到前面创建一个Web控制器。
完成后,可以对照gs servicing web content/complete中的代码检查结果。
从Spring初始化器开始
对于所有Spring应用程序,都应该从Spring初始化器开始。initializer提供了一种快速的方法来获取应用程序所需的所有依赖项,并为您进行了很多设置。这个例子需要Spring Web、Thymeleaf和Spring Boot DevTools依赖项。下图显示了为此示例项目设置的初始值设定项:
初始化程序
上图显示了选择Maven作为构建工具的初始化器。你也可以用格雷德。它还分别显示com.example和将web内容作为组和工件的值。您将在本示例的其余部分中使用这些值。

main()方法使用SpringBoot的Spring application.run()方法来启动应用程序。你注意到没有一行XML吗?也没有web.xml文件。这个web应用程序是100%纯Java的,您不必配置任何管道或基础设施。

构建可执行JAR

您可以使用Gradle或Maven从命令行运行应用程序。您还可以构建一个包含所有必要依赖项、类和资源的可执行JAR文件并运行它。构建一个可执行的jar使得在整个开发生命周期、不同环境等中将服务作为应用程序发布、版本化和部署变得非常容易。

如果使用Gradle,可以使用./gradlew bootRun运行应用程序。或者,可以使用./gradlew build构建JAR文件,然后运行JAR文件,如下所示:

java-jar build/libs/gs-serving-web-content-0.1.0.jar

如果使用Maven,可以使用./mvnw spring boot:run运行应用程序。或者,可以使用./mvnw clean包构建JAR文件,然后运行JAR文件,如下所示:

java-jar目标/gs-serving-web-content-0.1.0.jar

这里描述的步骤创建了一个可运行的JAR。您还可以构建一个经典的WAR文件。

显示日志输出。应用程序应该在几秒钟内启动并运行。

测试应用程序

现在该网站正在运行,请访问http://localhost:8080/greeting,在那里您将看到“Hello,World!”

通过访问http://localhost:8080/greeting提供名称查询字符串参数?name=用户。注意信息是如何从“你好,世界!“到”你好,用户!”:

此更改表明GreetingController中的@RequestParam安排按预期工作。name参数的默认值为World,但可以通过查询字符串显式重写它。

添加主页

静态资源,包括HTML、JavaScript和CSS,可以从您的Spring Boot应用程序中通过将它们放到源代码中的正确位置来提供。默认情况下,Spring Boot从位于/static(或/public)的类路径中的资源提供静态内容。index.html资源是特殊的,因为如果它存在,它将被用作“欢迎页面”,服务于web内容/这意味着它被用作根资源(即位于“http://localhost:8080/”)。因此,您需要创建以下文件(可以在src/main/resources/static/index.html中找到):

发布了0 篇原创文章 · 获赞 152 · 访问量 7051

猜你喜欢

转载自blog.csdn.net/blog_programb/article/details/105237904