基础环境参考文章:下载并运行一个Spring Boot基础项目
目标:浏览器访问项目URL,显示Hello World字符。
1、pom.xml中添加web模块支持
代码:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
pom.xml中有两个默认引入的依赖模块:
- spring-boot-starter:核心模块,包括自动配置支持、logging和YAML。(logging是指的Starter的专有框架;YAML是“另一种标记语言”的外语缩写,它参考了其他多种语言,包括:XML、C语言、Python、Perl以及电子邮件格式RFC2822)
- spring-boot-starter-test:测试模块,包含JUnit、 Hamcrest、Mockito测试框架
这里添加的spring-boot-starter-web模块作用是:构建Web、包含RESTful风格框架SpringMVC和默认的嵌入式容器Tomcat。(RESTful是一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件)
2、找到com.example.demo.controller包,新建一个HelloWorldController类。
代码:
package com.example.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController
{
@RequestMapping("/hello")
public String showText()
{
return "Hello World!";
}
}
3、找到DemoApplication.java类的main方法,右键选择Run As——Java Application
等待出现Started DemoApplication in XXX seconds
4、浏览器中输入http://localhost:8080/hello
注意:
测试结束后记得点这个红方块(Terminate)停止Spring Boot内建的Tomcat,否则容易造成下次启动项目成功但是在浏览器访问http://localhost:8080/hello出现Whitelabel Error Page的问题
小技巧:
按住shift+tab键,可减少代码缩进。