需求
需求:基于SpringBoot的方式开发一个Web应用,浏览器发起请求/hello后,给浏览器返回字符串"Hello World~"。

开发步骤
第一步:创建SpringBoot工程项目
第二步:定义HelloController类,添加方法hello,并添加注解
第三部:测试运行
创建SpringBoot工程(需要联网)
基于Spring官方骨架,创建SpringBoot工程。

基本信息描述完后,勾选Web开发相关依赖。

点击Finish之后,就会联网创建这个SpringBoot工程,创建好之后,结构如下:
● ==注意:在联网创建过程中,会下载相关资源(请耐心等待)==

定义请求处理类
在com.itheima这个包下创建一个子包controller

然后在controller包下新建一个类:HelloController
java
package com.itheima.controller;
import org.springframework.web.bind.annotation.*;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
System.out.println("Hello World ~");
return "Hello World ~";
}
}
运行测试
运行SpringBoot自动生成的引导类

打开浏览器,输入http://localhost:8080/hello

Web分析

浏览器:
● 输入网址:http://192.168.100.11:8080/hello
○ 通过IP地址192.168.100.11定位到网络上的一台计算机
我们之前在浏览器中输入的localhost,就是127.0.0.1(本机)
○ 通过端口号8080找到计算机上运行的程序
localhost:8080,意思是在本地计算机中找到正在运行的8080端口的程序
○ /hello是请求资源位置
■ 资源:对计算机而言资源就是数据
■ web资源:通过网络可以访问到的资源(通常是指存放在服务器上的数据)
localhost:8080/hello,意思是向本地计算机的8080端口程序,获取资源位置是/hello的数据
■ 8080端口程序,在服务器找/hello位置的资源数据,发给浏览器
服务器:(可以理解为ServerSocket)
● 接收到浏览器发送的信息(如:/hello)
● 在服务器上找到/hello资源
● 把资源发送给服务器
我们在JavaSE阶段学习网络编程时,有讲过网络三要素:
● IP:网络中计算机的唯一标识
● 端口:计算机中运行程序的唯一标识
● 协议:网络中计算机之间交互的规则
问题:浏览器和服务器两端进行数据交互,使用什么协议?
答案:http协议
入门程序解析
下面呢,我们在基于今天的核心技术点SpringBoot快速入门案例进行分析。
Spring官方骨架
之前我们创建的SpringBoot入门案例,是基于Spring官方提供的骨架实现的。
Spring官方骨架,可以理解为Spring官方为程序员提供一个搭建项目的模版。

我们可以通过访问:https://start.spring.io/,进入到官方骨架页面




Spring官方生成的SpringBoot项目,怎么使用呢?
● 解压缩后,就会得到一个SpringBoot项目工程

打开pom.xml文件,我们可以看到springboot项目中引入了web依赖和test依赖

结论:不论使用IDEA创建SpringBoot项目,还是直接在官方网站利用骨架生成SpringBoot项目,项目的结构和pom.xml文件中内容是相似的。
起步依赖
在我们之前讲解的SpringBoot快速入门案例中,同样也引用了:web依赖和test依赖

spring-boot-starter-web和spring-boot-starter-test,在SpringBoot中又称为:起步依赖
而在SpringBoot的项目中,有很多的起步依赖,他们有一个共同的特征:就是以spring-boot-starter-作为开头。在以后大家遇到spring-boot-starter-xxx这类的依赖,都为起步依赖。
起步依赖有什么特殊之处呢,这里我们以入门案例中引入的起步依赖做为讲解:
● spring-boot-starter-web:包含了web应用开发所需要的常见依赖
● spring-boot-starter-test:包含了单元测试所需要的常见依赖
spring-boot-starter-web内部把关于Web开发所有的依赖都已经导入并且指定了版本,只需引入spring-boot-starter-web依赖就可以实现Web开发的需要的功能

Spring的官方提供了很多现成的starter(起步依赖),我们在开发相关应用时,只需要引入对应的starter即可。
官方地址:https://docs.spring.io/spring-boot/docs/2.7.2/reference/htmlsingle/#using.build-systems.starters

每一个起步依赖,都用于开发一个特定的功能。
举例:当我们开发中需要使用redis数据库时,只需要在SpringBoot项目中,引入:spring-boot-starter-redis,即可导入redis开发所需要的依赖。
SpringBoot父工程
在我们之前开发的SpringBoot入门案例中,我们通过maven引入的依赖,是没有指定具体的依赖版本号的。

为什么没有指定<version>版本号,可以正常使用呢?
● 因为每一个SpringBoot工程,都有一个父工程。依赖的版本号,在父工程中统一管理。

内嵌Tomcat
问题:为什么我们之前书写的SpringBoot入门程序中,并没有把程序部署到Tomcat的webapps目录下,也可以运行呢?
原因呢,是因为在我们的SpringBoot中,引入了web运行环境(也就是引入spring-boot-starter-web七步依赖),其内部已经集成了内置的Tomcat服务器。
我们可以通过IDEA开发工具右侧的maven面板中,就可以看到当前工程引入的依赖。其中已经将Tomcat的相关依赖传递下来了,也就是说在SpringBoot中可以直接使用Tomcat服务器。

当我们运行SpringBoot的引导类时(运行main方法),就会看到命令行输出的日志,其中占用8080端口的就是Tomcat。