前言
基于原生的Servlet开发Web应用,过于繁琐,而使用SpringMVC实现Web应用,又需要很多配置信息,SpringBoot的出现,大大减轻了开发的流程,能够帮我们快速搭建一个Web应用并运行。
需求分析
需求:使用SpringBoot开发一个web应用,浏览器发起请求/hello后,给浏览器返回字符串"Hello World"。
开发步骤
一、创建springboot工程,并勾选web开发相关依赖
我使用的开发工具是idea2023,不同版本的idea创建项目的方式可能不同。
JDK版本:jdk1.8
新建项目
勾选web依赖
二、定义HelloController类,添加方法hello,并添加注解
因为是勾选依赖添加web应用,所以可能会出现一些模版代码,不需要可以先删除
HelloController

java
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
System.out.println("执行中...");
return "Hello World";
}
}
- @RestController注解:方法的返回值如果是String类型直接返回,如果是对象或集合类型,转换成Json格式并返回。
- @RequestMapping("/hello")注解:定义请求映射路径,我们在浏览器的地址栏输入localhost:8080/hello,就可以定位到hello()方法
三、运行测试
springboot内置了tomcat服务器,我们只需要运行启动器类就可以运行web项目

点击即可运行,注意端口默认为8080,如果出错,可以考虑端口占用问题。
在浏览器地址栏输入localhost:8080/hello,获得结果

此时查看后台:

同样执行成功!