第一步:建立一个Spring Boot项目
使用start.spring.io来创建一个Web项目。为了创建它,在“依赖(Dependencies)”对话框中搜索并添加“Spring Web”依赖,如下图所示。单击“生成(Generate)”按钮,下载ZIP压缩包并解压到你电脑的文件夹中。
由start.spring.io 创建的项目包含Spring Boot, 这个框架能为在你的app中运行Spring做好准备,并且不需要很多的代码或者配置。. Spring Boot是开始你的Spring项目的最快速和受欢迎的方式。
第二步:编写你的代码
在你的IDE中打开项目并在src/main/java/com/example/demo
文件夹下找到名为DemoApplication.java
的文件。现在通过增加在下方展示额外的方法和注解来改变文件的内容。你可以复制粘贴代码或直接键入它。
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}
我们刚才加入的hello()
方法被设计为接收一个String类型的名为name
的参数,然后在代码中把他和单词"Hello"
结合起来。这意味着如果你在请求中把name设置为"Amy"
,响应就会变成"Hello Amy"
。
@RestController
注解告诉Spring这段代码描述了一个在网络上可用的终端。@GetMapping("/hello")
告诉Spring使用我们的hello()
方法来答复被发送到地址http://localhost:8080/hello
的请求。最后@RequestParam
告诉Spring期望请求中含有一个name
值,但是如果没有name他将会使用默认值"World"
。
第三步:尝试运行
让我们构建并且运行程序。打开命令行(或终端)并且进入你存储项目文件的文件夹。我们可以通过执行如下命令来构建并运行应用:
MacOS/Linux:
./mvnw spring-boot:run
Windows:
mvnw spring-boot:run
你应当看到一些和下图非常相似的输出:
这里的最后几行告诉我们Spring已经启动了。Spring Boot内嵌的Apache Tomcat服务扮演着Web服务器的角色并且监听localhost
上8080
端口的请求。打开你的浏览器并且在顶部的地址栏中键入http://localhost:8080/hello 你应该得到一个友好的回应,像这样:
小测试
如果你在URL后添加?name=Amy
会发生什么?