官方教程体验:了解如何使用Spring MVC和Thymeleaf创建网页

使用 IDEA,提前安装好maven
先英原文后中翻,内容基本摘自官方教程

准备

官方教程:了解如何使用Spring MVC和Thymeleaf创建网页

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.

当你完成的时候,可以和 gs-serving-web-content/complete里面的内容对照一下

选择从中间开始

直接git clone, git clone https://github.com/spring-guides/gs-serving-web-content.git

在idea中打开initial项目

创建一个web的controller

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).
The following listing (from src/main/java/com/example/servingwebcontent/GreetingController.java) shows the controller:

在Spring构建网站的方法中,HTTP请求由一个控制器来处理。

你可以通过 @Controller 注解很容易识别控制器。

在下面的例子中,GreetingController通过返回一个 View(本例中的greeting)的名称来处理/greeting的GET请求。

下面的列表(来自 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";
	}

}

写代码(java)

新建一个java类,name = GreetingController
新建的GreetingController

把代码粘贴进去
粘贴controller代码

代码详解

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:

这款控制器简洁明了,但也有很多内容。我们一步一步地分解它。

@GetMapping注解确保了HTTP GET请求到/greeting的请求被映射到greeting()方法。

@RequestParam将查询字符串参数名称的值绑定到greeting()方法的name参数中。这个查询字符串参数不是必需的。如果请求中没有这个参数,则使用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>

写代码(html)

创建html文件
新建html
粘贴代码
粘贴代码

代码详解

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.

确保你的classpath上有Thymeleaf(artifact坐标:org.springframework.boot:spring-boot-starter-thymeleaf)。它已经在Github中的 "初始 "和 "完整 "样本中包含了。

配置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.

开发Web应用程序的一个常见特点是编码更改,重新启动你的应用程序,然后刷新浏览器查看更改。这整个过程会消耗大量的时间。为了加快这个刷新周期,Spring Boot提供了一个名为 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.

Spring Boot Devtools

  • 启用了热插拔功能。

  • 切换模板引擎,禁用缓存。

  • 启用LiveReload自动刷新浏览器。

  • 其他基于开发而非生产的合理缺失。

配置过程

查看pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

在initial已经有了

配置热更新

运行

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:

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

}

写代码(main application)

initial已经有了 打扰了

代码详解

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

@SpringBootApplication是一个方便的注释,它添加了以下所有内容。

  • @Configuration。标记该类作为应用程序上下文的Bean定义的来源。

  • @EnableAutoConfiguration。告诉Spring Boot根据classpath设置、其他Bean和各种属性设置开始添加Bean。例如,如果 spring-webmvc 在 classpath 上,这个注解会将应用程序标记为 web 应用程序,并激活关键行为,例如设置 DispatcherServlet

  • @ComponentScan: 告诉Spring在com/example包中寻找其他组件、配置和服务,让它找到控制器。

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.

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

构建

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

建立一个可执行的JAR

你可以用Gradle或Maven从命令行运行应用程序。你也可以建立一个可执行的JAR文件,包含所有必要的依赖、类和资源,然后运行。构建一个可执行的jar,可以让你在整个开发生命周期内,在不同的环境中,轻松地将服务作为一个应用程序进行发布、版本和部署。

如果你使用Gradle,你可以使用./gradlew bootRun来运行应用程序。另外,你也可以使用./gradlew build来构建JAR文件,然后运行JAR文件,如下所示。

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

如果你使用Maven,你可以使用./mvnw spring-boot:run运行应用程序。另外,你也可以用./mvnw clean package建立JAR文件,然后运行JAR文件,方法如下。

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

这里描述的步骤创建一个可运行的JAR。你也可以 建立一个经典的WAR文件

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

写代码

在idea里面就直接run就可以了

快捷键 shift + F10运行

测试

看看http://localhost:8080/greeting结果

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

现在网站正在运行,请访问http://localhost:8080/greeting,在这里你应该可以看到 “你好,世界!”
greeting

看看http://localhost:8080/greeting?name=User结果

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!”:

通过访问http://localhost:8080/greeting?name=User,提供一个名称查询字符串参数name。注意到消息从 "你好,世界!"变成了 “你好,用户!”。

user
实验了一下,中文也okk

中文实验网址http://localhost:8080/greeting?name=中文

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.

这个改动表明,GreetingController中的@RequestParam安排的工作原理与预期一致。name参数的默认值为World,但可以通过查询字符串显式覆盖。

添加主页

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, at http://localhost:8080/).
As a result, you need to create the following file (which you can find in src/main/resources/static/index.html):

添加一个主页

通过将静态资源(包括 HTML 和 JavaScript 和 CSS)丢到源代码中的正确位置,就可以从 Spring Boot 应用程序中服务于静态资源,包括 HTML 和 JavaScript 和 CSS。默认情况下,Spring Boot 从classpath中的/static(或/public)的资源中服务静态内容。index.html 资源很特别,因为如果它存在的话,它被用作 "欢迎页",“serving-web-content/”,这意味着它被作为根资源(也就是 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>

写代码

home

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

当你重新启动应用程序时,你会看到HTML在http://localhost:8080/

访问

报错了一次

报错
在idea重新run一下就可
home

小结

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

恭喜你! 你刚刚使用Spring开发了一个网页。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值