现在项目的开发基本都是依赖于SSM,即SpringBoot + SpringMVC + MyBatis,其中,SpringMVC 框架主要是用来便于开发者进行网页开发。Spring MVC 是基于 Servlet API 构建的原始 Web 框架,从⼀开始就包含在 Spring 框架中。
什么是MVC:
MVC 是 Model View Controller 的缩写,它是软件⼯程中的⼀种软件架构模式,它把软件系统分为模型、视图和控制器三个基本部分:

MVC 和 SpringMVC 的关系:
MVC 是⼀种思想,⽽ Spring MVC 是对 MVC 思想的具体实现。
创建SpringMVC 项目:
使用SpringBoot 来创建,只需要在创建项目时添加web依赖就可以:

1. 实现连接的功能:将⽤户(浏览器)和 Java 程序连接起来,也就是访问⼀个地址能够调⽤到我们的Spring 程序。
在 Spring MVC 中使⽤ @RequestMapping 来实现 URL 路由映射,也就是浏览器连接程序的作⽤。
路由映射:所谓的路由映射指的是,当用户访问⼀个 url 时,将⽤户的请求对应到程序中某个类的某个⽅法的过程就叫路由映射。
@RequestMapping 即可修饰类,也可以修饰⽅法,当修饰类和⽅法时,访问的地址是类 + ⽅法(类和方法上方注解中的value值);当只有方法被修饰时,直接访问方法就可以,此外该注解支持多种http请求方法,通过修改method属性值进行更改。


仅支持单一http方法的注解:

2.实现获取参数的功能
2.1 获取单个参数
当@RequestMapping注解中的value值不加"/"时,会根据类上的注解中的value值进行相对路径的定位。一般情况下还是加"/"比较好,防止出错。


2.2 获取多个参数

传入的多个参数之间用"&"连接:

获取多个参数,并对参数重命名,该情况是发生在前后端对参数的命名不一致时使用:


@RequestParam 注解默认情况下其修饰的变量为必须传入,不传参会报错,修改其属性,required = false 即可改变,另外,该注解主要是用于获取HTTP get方法中的query string信息,也就是utl中"?"之后的参数。

修改后:


2.3 获取一个对象
普通格式的数据:


json 格式的数据(通过postman来构造数据):

@RequestBody 注解,主要是用于获取post请求中body部分的数据,根据请求头中的Content-Type来确定body部分的数据,再根据代码中的参数类型进行参数的转换:

2.4 从基础URL 中获取参数
@PathVailable 注解,主要是用于从URL 基础路径中获取参数,也就是从URL "?"之前的路径中获取参数,其默认情况下也是要必须传入参数,否则会报错,通过required属性进行修改:


2.5 上传文件
@RequestPart 注解用于将 multipart/form-data 类型的请求映射到控制器处理方法的参数中。这个注解可以用于处理文件上传的情况。

使用postman 来上传文件:

此时,还存在一个问题,后续上传的文件会将前面的文件覆盖,解决办法,对每次上传的文件给一个独一无二的文件名:

2.6 获取cookie
传统方式获取cookie:

在网页设置两个cookie:

查看运行结果:

通过注解来获取cookie:

运行结果:

2.7 获取header
传统方式:


通过注解来获取:


2.8 获取session
先进行session 的设置,然后进行获取:

运行结果:

3. 返回数据
3.1 返回非静态页面数据
类上方加注解 @RequestBody,上述获取到数据,并在页面显示均是这种方式。
3.2 返回静态页面数据
去掉上述注解,返回静态页面文件:


3.3 请求转发和请求重定向
forward: 请求转发
redirect: 请求重定向
区别:
-
请求重定向(redirect)将请求重新定位到资源;请求转发(forward)服务器端转发。
-
请求重定向地址发⽣变化,请求转发地址不发⽣变化。
-
请求重定向与直接访问新地址效果⼀直,不存在原来的外部资源不能访问;请求转发服务器端转发有可能造成原外部资源不能访问。
示例:
请求转发:

url 地址不发生变化:

请求重定向:

可以看到在请求发送的一瞬间,url发生变化:

下面代码中,第一部分执行成功,第二部分无法访问,因为请求转发是由服务器访问,其无法访问外部资源。


SpringBoot 开启热部署
添加依赖(图示添加是使用的Edit Starters插件):

需要在当前项目和新项目部分都做更改:

当前项目:


新项目:
