使用 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 aView
(in this case,greeting
).
The following listing (fromsrc/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
把代码粘贴进去
代码详解
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 thegreeting()
method.
@RequestParam
binds the value of the query string parametername
into thename
parameter of thegreeting()
method. This query string parameter is notrequired
. If it is absent in the request, thedefaultValue
ofWorld
is used. The value of thename
parameter is added to aModel
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 thegreeting.html
template and evaluates theth:text
expression to render the value of the${name}
parameter that was set in the controller.
The following listing (fromsrc/main/resources/templates/greeting.html
) shows thegreeting.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文件
粘贴代码
代码详解
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 (fromsrc/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, ifspring-webmvc
is on the classpath, this annotation flags the application as a web application and activates key behaviors, such as setting up aDispatcherServlet
.@ComponentScan
: Tells Spring to look for other components, configurations, and services in thecom/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’sSpringApplication.run()
method to launch an application. Did you notice that there was not a single line of XML? There is noweb.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, visithttp://localhost:8080/greeting
, where you should see “Hello, World!”
现在网站正在运行,请访问http://localhost:8080/greeting
,在这里你应该可以看到 “你好,世界!”
看看http://localhost:8080/greeting?name=User结果
Provide a
name
query string parameter by visitinghttp://localhost:8080/greeting?name=User
. Notice how the message changes from “Hello, World!” to “Hello, User!”:
通过访问http://localhost:8080/greeting?name=User
,提供一个名称查询字符串参数name
。注意到消息从 "你好,世界!"变成了 “你好,用户!”。
实验了一下,中文也okk
中文实验网址http://localhost:8080/greeting?name=中文
This change demonstrates that the
@RequestParam
arrangement inGreetingController
is working as expected. Thename
parameter has been given a default value ofWorld
, 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
). Theindex.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 insrc/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>
写代码
When you restart the application, you will see the HTML at
http://localhost:8080/
.
当你重新启动应用程序时,你会看到HTML在http://localhost:8080/
。
访问
报错了一次
在idea重新run一下就可
小结
Summary
Congratulations! You have just developed a web page by using Spring.
恭喜你! 你刚刚使用Spring开发了一个网页。