文章目录
第一章 Spring MVC简介
1.1 MVC的概念
MVC是一种软件架构的思维,将软件按照模型,视图,控制器来换分
-
M:Model,模型层,指工程中的JavaBean,作用是处理数据
JavaBean分为两类:
一类成为实体类Bean,专门存储数据业务,如POJO实体类
一类成为业务处理Bean,指Service或者Dao对象,专门用于处理业务逻辑或和数据访问 -
V:View,视图层,指工程中的html或者jsp页面,作用是与用户进行交互,展示数据
-
C:Controller,控制层,指工程中的Servlet,作用是接收请求和响应浏览器
MVC工作流程:
1)用户通过视图层发送请求到服务器,在服务器中请求被Controller接收,
2)Controller调用相应的Model层处理请求,处理完毕将结果返回给Controller。
3)Controller再根据请求的结果找到相应的View视图,渲染数据后最终响应给浏览器
MVC流程图:

1.2 Spring MVC 介绍
SpringMVC是Spring的一个后续产品,,是Spring的一个子项目。SpringMVC是Spring为表述层开发提供的一套完备的解决方案,目前普遍使用SpringMVC作为javaEE项目表述层的首选方案
备注:三层架构分为表述层,业务逻辑层,数据访问层,表述层是表示前台页面和后台servlet
1.3 Spring MVC 特点
SpringMVC是Spring框架的一个子项目,与IOC容器无缝对接。基于原生的Servlet,通过功能强大的前端控制器DispatcherServlet,对请求和响应进行统一处理。代码清晰简洁,大幅度提升开发效率。内部组件化程度高,可插拔式组件,即插即用。性能卓著,尤其适合大型互联网项目的要求
第二章 环境搭建
2.1 开发环境
IDEA 2021.3
Maven 3.6.3
MariaDB:10.3.7
Tomcat 9
Spring 5.3.7
2.2 创建maven工程
1 添加web模块
2 打包方式 war
<packaging>war</packaging>
3 引入依赖
<dependencies>
<!--springmvx-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.7</version>
</dependency>
<!--日志-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!--ServletPI-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--spring和thymeleaf整合包-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.15.RELEASE</version>
</dependency>
</dependencies>
2.3 配置web.xml
注册SpringMVC的前端控制器:dispatcherServlet
1 默认配置方式
在配置作用下,SpringMVC的配置文件默认位于WEB-INF下
默认名称为< servlet-name >-servlet.xml
文件名为:SpringMVC-servlet.xml
设置SpringMVC的核心控制器所能处理的请求的请求路径
/ 匹配的请求可以是/login或.html或.css或.js等方式的额请求路径
但是不能匹配 .jsp 请求路径的请求
<!--配置SpringMVC的前端控制器-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<!--
设置SpringMVC的核心控制器所能处理的请求的请求路径
/ 匹配的请求可以是/login或.html或.css或.js等方式的额请求路径
但是不能匹配 .jsp 请求路径的请求
-->
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
2 扩展配置方式 - 常用方式
可通过init-param标签设置SpringMVC配置文件的位置和名称,
通过load-on-startup标签设置SpringMVC前端控制器DispatcherServlet的初始化时间
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置SpringMVC的前端控制器-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--通过初始化参数指定SpringMVC配置文件的位置和名称-->
<init-param>
<!--contextConfigLocation固定设置-->
<param-name>contextConfigLocation</param-name>
<!--使用classpath:表示从类路径找到配置文件
例如:maven工程中的src/main/resources
-->
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--将前端控制器DispatcherServlet初始化时间提前到服务器启动时-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<!--
设置SpringMVC的核心控制器所能处理的请求的请求路径
/ 匹配的请求可以是/login或.html或.css或.js等方式的额请求路径
但是不能匹配 .jsp 请求路径的请求
-->
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
< url-pattern >标签中使用 / 和 / * 的区别
/ 匹配的请求可以是/login或.html或.css或.js方式的请求路径。但是/不能匹配.jsp请求路径的请求,因此就可以在避免访问jsp页面时,该请求被DispatcherServlet处理,从而找不到相应的页面
/ * 能够匹配所有请求
2.4 创建请求控制器
- 1、请求控制器:
由于前端控制器对浏览器发送的请求进行了统一的处理,但是具体的请求有不同的处理过程,因此要创建具体的请求类,即请求控制器 - 2、控制器方法:
请求控制器中每一个处理请求的方法称为控制器方法。因为SpringMVC的控制器由一个普通Java类担任,因此需要通过@Controller注解将其标识为一个控制器组件,交给Spring容器IOC管理,此时SpringMVC才能识别控制器的存在
2.5 创建Spring MVC的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress ALL -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--配置扫描组件-->
<context:component-scan base-package="com.zzy.controller"></context:component-scan>
<!--配置thymeleaf视图解析器-->
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="order" value="1"></property>
<property name="characterEncoding" value="UTF-8"></property>
<property name="templateEngine">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver">
<bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<!--视图前缀-->
<property name="prefix" value="/WEB-INF/templates/"/>
<!--视图后缀-->
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8"/>
</bean>
</property>
</bean>
</property>
</bean>
</beans>
2.6 测试案例
@Controller
public class HelloController {
/*
访问:WEB-INF/templates/index.html
*/
@RequestMapping(value = "/")
public String index(){
//返回视图的名称
return "index";
}
}
配置tomcat
DEBUG运行
其中 /springmvc/ 表示上下文路径
请求跳转,跳转到target.html页面,
本质是请求的转发,地址栏未发生改变
<body>
<h1>首页</h1>
<!--@{} 表示绝对路径,资源写在大括号中-->
<a th:href="@{/target}">访问目标页面target.html</a>
</body>
在请求控制器中创建处理请求的方法:
@RequestMapping("/target")
public String target(){
return "target";
}
2.7 总结
1 浏览器发送请求,若请求地址符合前端控制器的url-pattern,
2 该请求会被前端控制器DispatcherServlet处理,
3 前端控制器会读取SpringMVC的核心配置文件,通过扫描组件找到控制器
4 将请求地址和控制器中的@RequestMapping的value属性值进行匹配
5 若匹配成功,该注解所标识的控制器方法就是处理请求的方法
6 处理请求的方法需要返回一个字符串类型的视图名称,
7 该视图名称会被视图解析器解析,加上前缀和后缀组成视图的路径,
8 通过thymeleaf对视图进行渲染,最终转发到视图所对应的页面
第三章 @RequestMapping注解详解
3.1 功能
从注解的名称上可以看到,
@RequestMapping注解的作用是:
将请求和处理请求的控制器方法关联起来,建立映射关系。
SpringMVC接收到指定的请求,就回来找到在映射关系中对应的控制器方法来处理这个请求
3.2 位置
@RequestMapping标识一个类,设置映射请求的请求路径的初始信息
@RequestMapping标识一个方法,设置映射请求路径的具体信息
@Controller
@RequestMapping("/req")
public class ReqMappingController {
/*
测试@RequestMapping 位置的使用
*/
@RequestMapping("/testRequestMapping")
public String testReqMapping(){
return "success";
}
}
1 thymeleaf中的@{}的含义:
thymeleaf中的@{}:表示获取应用的上下文路径
等同于Jsp 的老方法:
${pageContext.request.contextPath} = @{}
jsp中获取上下文路径拼接资源路径:
th:action= "${pageContext.request.contextPath}/upload
thymeleaf中获取上下文路径拼接资源路径:
th:action= "@{/upload}
2 为什么 Tomcat 运行时默认打开 index.html,或者 index.jsp
Tomcat 安装目录下的 conf\web.xml 包含所有项目的配置信息
如果 IDEA 中的 web.xml 没有相关的配置信息,
就运行 Tomcat 安装目录下的 conf\web.xml。
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
如果需要修改模块的欢迎页面也是可以的,
只需要在当前模块的 web.xml 文件配置即可
<welcome-file-list>
<welcome-file>love.html</welcome-file>
</welcome-file-list>
3.3 value属性
@RequestMapping注解的value属性通过请求的请求地址匹配请求映射
@RequestMapping注解的value属性是一个字符串类型的数组,
表示该请求映射能够匹配多个请求地址所对应的请求
@RequestMapping注解的value属性必须设置,至少通过请求地址匹配请求映射
<a th:href="@{/req/testValue1}">测试@RequestMapping注解value属性--/testValue1</a><br>
<a th:href="@{/req/testValue2}">测试@RequestMapping注解value属性--/testValue2</a><br>
/*
测试@RequestMapping 的value属性
value中可以声明多个请求,只需满足任意一个即可
*/
@RequestMapping(value = {"/testValue1","/testValue2"})
public String testValue(){
return "success";
}
3.4 method属性
@RequestMapping注解的method属性通过请求的请求方式(GET/POST)匹配请求映射
@RequestMapping注解的method属性是一个RequestMethod类型的数组,
表示请求映射能能够匹配多种请求方式的请求
若当前请求的请求地址满足请求映射的value属性,
但是请求方式不满足method属性,则浏览器报405.Request method ‘POST’ not support
<form th:action="@{/req/testMethod}" method="post">
<input type="submit" value="测试@RequestMapping注解的method属性1">
</form>
<form th:action="@{/req/testMethod}" method="get">
<input type="submit" value="测试@RequestMapping注解的method属性2">
</form>
/*
测试@RequestMapping 的method属性
method中可以声明多个请求方式,
在满足value属性表的前提下,
只要满足任意一种请求方式即可
*/
@RequestMapping(value = "/testMethod",method = {RequestMethod.GET,RequestMethod.POST})
public String testMethod(){
return "success";
}
备注:
1 兑取处理指定请求方式的控制器方法,
SpringMVC中提供了@RequestMapping的派生注解
处理GET请求的映射:GetMapping
处理POST请求的映射:PostMapping
处理PUT请求的映射:PutMapping
处理DELETE请求的映射:DeleteMapping
2 常用的请求方式有get post put delete:
但目前浏览器只支持get和post,若在form表单提交时,
为method设置了其他请求方式的字符串,put或者delete,
则按照默认的GET请求方式处理
若要发送put和delete请求,
则需要通过spring提供的过滤器HiddenHttpMethodFilter。
3.5 params属性
@RequestMapping注解的headers属性通过请求的请求参数匹配请求映射
@RequestMapping注解的headers属性是一个字符串类型的数组,
可以通过四种表达式设置请求参数和请求映射的匹配关系
‘param’:要求请求映射所匹配的请求必须携带param请求参数
‘!param’:要求请求映射所匹配的请求必须携带param请求参数
‘param=value’:要求请求映射所匹配的请求必须携带param请求参数,且param=value
‘param!=value’:要求请求映射所匹配的请求必须携带param请求参数,但是param=value
<a th:href="@{/req/testParam(username='tom',password=123456)}">测试@RequestMapping注解的param属性</a><br>
/*
测试param属性,同时满足username和password
*/
@RequestMapping(value = {"/testParam"},
params = {"username","password"})
public String testParam(String username,String password){
System.out.println(username+password);
return "success";
}
注意:
若当前请求满足@RequestMapping注解的value和method属性,但是不满足params属性,
此时页面会报400错误
Parameter conditions "username,password" not met for actual
request parameters: username={tom}, password={123456}
3.6 headers属性
@RequestMapping注解的headers属性通过请求的请求头信息匹配请求映射
@RequestMapping注解的headers属性是一个字符串类型的数组,
可以通过四种表达式设置请求头信息和请求映射的匹配关系
‘header’,要求请求映射所匹配的请求必须携带header请求头信息
‘!header’:要求请求映射所匹配的请求不能携带header请求头信息
‘header=value’:要求请求映射所匹配的请求必须携带header请求头信息,且header=value
‘header!=value’:要求请求映射所匹配的请求必须携带header请求头信息,且header!=value
若当前请求满足@RequestMapping和value和method属性,但不满足headers属性,此时页面报404错误,即资源未找到
<a th:href="@{/req/testHeader(username='tom',password=123456)}">测试@RequestMapping注解的headers属性</a><br>
/*
测试headers属性
*/
@RequestMapping(value = {"/testHeader"},
params = {"username","password"},
headers = ("Host=localhost:8085"))
public String testHeader(){
return "success";
}
3.7 路径占位符
原始方式:/deleteById?id=1
rest方式:/deleteById/1
SpringMVC路径中的占位符常用语restful风格中,
当请求路径中将某些数据通过路径的方式传输到服务器中,
就可以在相应的@RequestMapping注解的value属性中通过占位符{xxx}表示传输的数据,
再通过@PathVariable注解,将占位符所表示的数据赋值给控制器方法的形参
注意:路径中的占位符名称必须和@PathVariable中的value属性值一致
<a th:href="@{/req/testPath/1}">测试@RequestMapping注解支持路径中的占位符</a><br>
/*
测试路径占位符{},
路径中的占位符名称必须和@PathVariable中的value属性值一致
*/
@RequestMapping("/testPath/{id}")
public String testPath(@PathVariable(value = "id") Integer ids){
System.out.println(ids);
return "success";
}
第四章 SpringMVC获取请求参数
4.1 servletAPI获取请求参数
将HttpServletRequest作为控制器方法的形参,
此时HttpServletRequest类型的参数表示封装了当前请求报文的对象
<a th:href="@{/testServletAPI(username='admin',password=123456)}">通过servletAPI获取请求参数</a><br>
/*
1 通过servletAPI获取请求参数
*/
@RequestMapping("/testServletAPI")
//形参位置的request表示当前的请求的封装对象
public String testServletAPI(HttpServletRequest request){
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username+password);
return "success";
}
4.2 方法形参获取请求参数
在控制器方法的形参位置,设置和请求参数同名的形参,
当浏览器发送请求,匹配到请求映射时,在DispatcherServlet中。
就会将请求参数赋值给相应的形参
<a th:href="@{/testMethodParam(username='admin',password=123)}">通过控制器方法的形参获取请求参数</a><br>
<form th:action="@{/testMethodParam2}" method="get">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"/><br>
爱好:<input type="checkbox" name="hobby" value="篮球"/>篮球
<input type="checkbox" name="hobby" value="足球"/>足球
<input type="checkbox" name="hobby" value="羽毛球"/>羽毛球<br>
提交:<input type="submit" value="通过控制器方法的形参获取请求参数">
</form>
/*
2 通过控制器方法的形参获取请求参数 GET
*/
@RequestMapping("/testMethodParam")
//形参位置的request表示当前的请求的封装对象
public String testMethodParam(String username,String password){
System.out.println(username+password);
return "success";
}
@RequestMapping(value = "/testMethodParam2")
//形参位置的request表示当前的请求的封装对象
public String testMethodParam2(String username,String password,String[] hobby){
//若请求参数中出现多个同名的请求参数,
// 可以在控制器方法的形参位置设置字符串类型,或者字符串数组接受参数
//使用字符串,参数值会使用逗号拼接
System.out.println(username+password+ Arrays.toString(hobby));
return "success";
}
注:
若请求所传输的请求参数中有多个同名的请求参数,
此时可以在控制器方法的形参中:
设置字符串数组或者字符串类型的形参接收此请求参数
若使用字符串数组类型的形参,此参数的数组中包含了每一个数据
若使用字符串类型的形参,此参数的值为每个数据中间使用逗号拼接的结果
4.3 @RequestParam
@RequestParam是将请求参数与控制器方法的形参创建映射关系
@RequestParam注解一共有三个属性:
value:指定为形参赋值的请求参数的参数名
required 设置是否必须传输此请求参数,默认值为true
若设置为true时,则当前请求必须传递value所指定的
请求参数,若没有传递该请求参数,且没有设置defaultValue属性,
则页面报400错误,
若设置为false,则当前请求不是必须传输value所指定的请求参数
若没有传输,则注解所表示的形参为null
defaultValue属性:不管required属性值为true或false,
当value所指定的请求参数没有传输时,则使用默认值为形参赋值
<a th:href="@{/testRequestParam(user_name='admin',password=123)}">@RequestParam是将请求参数与控制器方法的形参创建映射关系</a><br>
/*
3 测试@RequestParam注解:为请求参数创建映射关系
*/
@RequestMapping("/testRequestParam")
//形参位置的request表示当前的请求的封装对象
public String testRequestParam(@RequestParam(value = "user_name",required = true,defaultValue = "张三") String username, String password){
System.out.println(username+password);
return "success";
}
4.4 @RequestHeader
@RequestHeader是将请求头信息和控制器方法的形参创建映射关系
@RequestHeader注解:
一共有三个属性:value required defaultValue
用法同@RequestParam类似
<a th:href="@{/testRequestHeader(user_name='admin',password=123)}">@RequestHeader是将请求参数与控制器方法的形参创建映射关系</a><br>
/*
4 测试@RequestHeader注解:为请求参数创建映射关系
*/
@RequestMapping("/testRequestHeader")
//形参位置的request表示当前的请求的封装对象
public String testRequestHeader(String username, String password,@RequestHeader(value = "host") String host){
System.out.println(username+password);
System.out.println(host);
return "success";
}
4.5 @CookieValue
@CookieValue是将请求头信息和控制器方法的形参创建映射关系
@CookieValue注解:
一共有三个属性:value required defaultValue
用法同@RequestParam类似
<a th:href="@{/testCookieValue(username='admin',password=123456)}">通过servletAPI获取测试@CookieValue注解</a><br>
/*
5 通过servletAPI获取测试@CookieValue注解
*/
@RequestMapping("/testCookieValue")
//形参位置的request表示当前的请求的封装对象
public String testCookieValue(HttpServletRequest request,@CookieValue(value = "JSESSIONID") String JSESSIONID){
//第一次访问请求方法,会创建session,此时cookie会存在于响应头中
//第二次访问此方法,请求头中就会携带cookie信息
HttpSession session = request.getSession();
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(JSESSIONID);
System.out.println(username+password);
return "success";
}
4.6 pojo获取请求参数
可以在控制器方法的形参位置设置一个实体类型的参数,
此时若浏览器传输的请求参数的参数名和实体类中的属性名一致,
那么请求参数就会为此属性赋值
<form th:action="@{/testPOJO}" method="post">
用户名:<input type="text" name="username"/><br>
密码:<input type="password" name="password"/><br>
性别:<input type="radio" name="sex" value="男"/>男
<input type="radio" name="sex" value="女"/>女<br>
年龄:<input type="text" name="age"><br>
邮箱:<input type="text" name="email"><br>
提交:<input type="submit" value="使用实体类接受请求参数">
</form>
/*
6 测试通过POJO获取请求参数
*/
@RequestMapping(value = "/testPOJO")
public String testPOJO(User user){
System.out.println(user);
return "success";
}
4.9 解决获取请求参数的乱码问题
解决请求参数的乱码问题,可以使用SpringMVC提供的编码过滤器
CharacterEncodingFilter,但是必须在web.xml中配置
注:SpringMVC中处理编码的过滤器一定要配置到其他过滤器之前,否则无效
在web.xml中配置过滤器,在servlet初始化之前设置好编码格式。
web容器三大组件:listener 、filter、servlet
其中listener负责监听容器
filter负责过滤资源
servlet负责处理请求响应数据
其先后顺序是:listener 、filter、srvlet
注:tomcat的server.xml中配置的URIEncoding=UTF-8,
只针对GET请求的字符编码生效,
对于POST请求不起作用,顾需要上述在web.xml中的操作
<!--配置过滤器-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
第五章 域对象共享数据
5.1 servletAPI向request域对象共享数据
request域对象中存放键值对,页面通过${键的名称}获取对应的值
<p th:text="${username}"></p>
/*
1 使用servletAPI向request域对象中共享数据
*/
@RequestMapping("/testRequestByServletAPI")
public String testRequestByServletAPI(HttpServletRequest request){
//request域对象中存放键值对,页面通过${键的名称}获取对应的值
request.setAttribute("username", "hello servlet");
return "success";
}
5.2 ModelAndView向request域对象共享数据
ModelAndView中的model和view的功能
Model主要向请求域中共享数据
View主要用于设置视图,实现页面跳转
<p th:text="${MAV}"></p>
/*
2 使用ModelAndView向request域对象中共享数据
*/
@RequestMapping("/testModelAndView")
public ModelAndView testRequestByServletAPI(){
ModelAndView modelAndView = new ModelAndView();
//处理模型数据,即向请求域request共享数据
modelAndView.addObject("MAV", "hello ModelAndView");
//设置跳转的视图名称
modelAndView.setViewName("success");
return modelAndView;
}
5.3 Model向request域对象共享数据
<p th:text="${model}"></p>
/*
3 使用Model向request域对象中共享数据
*/
@RequestMapping("/testModel")
public String testModel(Model model){
model.addAttribute("model","hello model");
return "success";
}
5.4 Map向request域对象共享数据
<p th:text="${map}"></p>
/*
4 使用Map向request域对象中共享数据
*/
@RequestMapping("/testMap")
public String testMap(Map map){
map.put("map", "hello map");
return "success";
}
5.5 ModelMap向request域对象共享数据
<p th:text="${modelMap}"></p>
/*
5 使用ModelMap向request域对象中共享数据
*/
@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelMap){
modelMap.addAttribute("modelMap", "hello modelMap");
return "success";
}
5.6 Model、Map、ModelMap的区别
Model、Map、ModelMap类型的参数其实本质上都是BindingAwareModelMap
public interface Model
public class ModelMap extends LinkedHashMap<String, Object>
public class LinkedHashMap<K,V> extends HashMap<K,Vi> mplements Map<K,V>
public class ExtendedModelMap extends ModelMap implements Model
public class BindingAwareModelMap extends ExtendedModelMap
5.7 向session域共享数据
通过session.键名获取session中的数据
<p th:text="${session.name}"></p>
/*
6 使用session域对象中共享数据
*/
@RequestMapping("/testSession")
public String testSession(HttpServletRequest request){
HttpSession session = request.getSession();
session.setAttribute("name", "hello session");
return "success";
}
5.8 向application域共享数据
(application也是就是ServletContext上下文)
通过application域对象.键名获取域对象中的数据
<p th:text="${application.name}"></p>
/*
7 使用application域对象中共享数据
*/
@RequestMapping("/testApplication")
public String testApplication(HttpServletRequest request){
ServletContext context = request.getSession().getServletContext();
context.setAttribute("name", "hello app");
return "success";
}
第六章 SpringMVC的视图
SpringMVC中的视图是view接口,
视图的作用是:渲染数据,将模型Model中的数据展示给用户。
SpringMVC视图的种类很多,默认有转发视图和重定向视图
当工程引入jstl依赖,转发视图hi自动转换为jstlView
若使用的视图技术是Thymeleaf,
在SpringMVC的配置文件中配置了视图解析器,
由此视图解析器解析之后所得到的是ThymeleafView
6.1 ThymeleafView
当控制器方法中所设置的视图的视图名没有任何前缀时,
此时的视图名会被SpringMVC配置文件中配置的视图解析器所解析,
视图名称拼接视图前缀和视图后缀所得到的的最终路径,
会通过转发的形式实现跳转
<a th:href="@{/testThymeleafView}">测试ThymeleafView</a><br>
/*
1 测试ThymeleafView视图
*/
@RequestMapping(value = "/testThymeleafView")
public String testThymeleafView(){
return "success";
}
6.2 转发视图
SpringMVC中默认的转发视图是internalResourceView
SpringMVC中创建转发视图的情况:
当控制器方法所设置的视图名称以forward为前缀时,创建internalResourceView视图,
此时的视图名称不会被SpringMVC配置文件中所配置的视图解析器解析,
而是会将前缀forward去掉,剩余部分作为最终版路径通过转发的方式实现跳转
<a th:href="@{/testForward}">测试转发视图</a><br>
/*
2 测试internalResourceView视图,转发视图
*/
@RequestMapping("/testForward")
public String testForward(){
//需要转发的路径
return "forward:/testThymeleafView";
}
步骤:
访问 “/testForward” 映射的方法,执行转发操作,
进而访问 “ /testThymeleafView ”,最终跳转到success页面
此过程中,浏览器的地址栏路径未发生改变,请求转发是一次请求
6.3 重定向视图
SpringMVC中默认的重定向视图是RedirectView
当控制器方法中所设置的视图名称是以“ redirect ”为前缀时,创建RedirectView视图,
此时的视图名称不会被SpringMVC配置文件中的视图解析器解析,
而是会将前缀redirect去掉,剩余的部分作为最终路径通过重定向的方式实现跳转
<a th:href="@{/testRedirect}">测试RedirectView重定向视图</a><br>
/*
3 测试RedirectView视图,重定向视图
*/
@RequestMapping("/testRedirect")
public String testRedirect(){
//需要转发的路径
return "redirect:http://www.baidu.com";
}
6.4 转发和重定向的区别
转发:服务器端的行为
request.getRequestDispatcher().forward(request,respond)
转发在服务器端发挥作用,
通过forward()方法提交信息在多个页面之间进行传递。
转发的特点是:
1.地址栏不会改变
2.转发只能转发到当前Web应用内的资源
3.在转发过程中,可以将数据保存到request域对象当中去
4.转发只有一次请求
5.转发是服务器端行为
转发的过程:
1.客户端浏览器发送http
2.web浏览器接收请求
3.调用内部的一个方法在容器内部完成请求处理和转发工作
需注意的是:转发的路径必须是同一个web容器下的url。
在客户端浏览器路径栏显示的仍然是第一次访问的路径。
转发行为是浏览器只做了一次访问请求。
重定向:客户端的行为
resp.sendRedirect(" ")
重定向的特点:
1.重定向地址栏会改变
2.重定向可以跳转到当前web应用,甚至是外部域名的网站。
3.不能在重定向的过程中,将数据保存到request域对象中。
重定向的过程:
1.客户端浏览器发送http请求
2.web服务器接收后,发送302状态码响应,
并且发送location给客户端服务器。
3.客户端服务器发现是302响应后,则自动发送一个http请求,
请求url为重定向的地址,响应的服务器根据此请求
寻找资源并发送给客户。
转发和重定向的区别;
(1)请求转发是一次请求一次响应,而重定向是两次请求两次响应;
(2)请求转发地址栏不会改变,而重定向地址栏会显示第二次请求的地址;
(3)请求转发只能转发给本项目的其他资源,
而重定向不仅可以重定向到本项目的其他资源,
还可以重定向到其他项目;
(4)请求转发是服务器端的行为,转发时只需要给出转发的资源路径即可,
如Servlet的访问路径;而重定向需要给出全路径,
即路径要包含项目名;
(5)请求转发比重定向的效率高,因为请求转发是一个请求。
在以后的开发中,如果需要地址栏的地址发生改变,
就选择重定向;如果需要在Servlet之间通过request域进行数据通信,
就选择请求转发
6.5 视图控制器 view-controller
当控制器方法中,仅仅用来实现页面跳转,即需要设置视图名称时,
可以将处理器方法使用view-controller标签进行展示
通过SpringMVC的核心配置文件中配置视图控制器,代替访问首页的功能
前提是必须在开启注解驱动的条件下使用,否则控制器中的方法映射均失效
path:设置处理的请求地址
view-name:设置请求地址所对应的视图名称
<!--配置视图控制器 需要配合注解驱动的配置使用-->
<mvc:view-controller path="/" view-name="index"></mvc:view-controller>
<!--k开启注解驱动-->
<mvc:annotation-driven/>
使用视图控制器配置代替此方法访问首页
/*
使用视图控制器配置代替此方法访问首页
*/
@RequestMapping("/")
public String testIndex(){
return "index";
}
注:
当SpringMVC中设置任何一个view-controller时,
其他控制器中的请求映射将全部失效,
此时需要在SpringMVC核心配置文件中设置开启mvc注解驱动标签:
<mvc:annotation-driven/>
6.6 访问jsp使用的视图解析器
在jsp中使用到的也是InternalResourceView视图
<!--配置jsp视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/templates/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
JSP中获取上下文路径的方式:
<a href="${pageContext.request.contextPath}/testJsp">测试jsp</a>
使用JSP页面的最小域对象pageContext:
其属性request的属性contextPath得到上下文路径
${pageContext.request.contextPath}
首页的位置 。被访问资源的位置
第七章 RESTFul
7.1 RESTFul间介
REST:即Representational State Transfer ,表现层资源状态转移
资源:
资源是一种看待服务器的方式
资源的表述:
资源的表述是对资源在某个特定时刻的状态描述,
可以在客户端-服务端之间转移交换,资源的表述可以有多种格式,
例如HTML/XML/JSON/纯文本/图片/音频/视频。
资源的表述格式可以通过协商机制来确定,
请求-响应方向的表述通常使用不同的形式。
状态转移:
是指在客户端和服务端之间转移代表资源状态的表述,
通过转移和操作资源的表述,来间接实现操作资源的目的
7.2 RESTFul的实现
具体来说就是HTTP协议里面,四个表示操作方式的动词,GET PUT DELETE POST
它们分别对应四种操作:
GET 用来获取资源
PUT 用来更新资源
DELETE 用来删除资源
POST 用来新建资源
REST风格提倡URL地址使用统一的风格设计,
从前到后各个单词使用斜杠分开
不使用问号键值对方式携带请求参数,
而是将要发送给服务器的数据作为URL地址的一部分,
以保证整体风格的一致性。

7.3 HiddenHttpMethodFilter
由于浏览器只支持发送POST和GET请求,针对PUT和DELETE请求,
SpringMVC提供了HiddenHttpMethodFilter帮助我们将POST请求转化成DELETE或者PUT请求
HiddenHttpMethodFilter处理DELETE和PUT请求的条件:
当前请求的方式必须是POST请求
当前请求必须传输请求参数_method
<input type="hidden" name="_method" value="put">
<form th:action="@{/user}" method="post">
<input type="hidden" name="_method" value="put">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
提交:<input type="submit" name="修改用户信息学"><br>
</form>
第八章 RESTFul案例
8.1 准备工作
1 创建demo05

2 配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置编码过滤器-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!--设置请求编码-->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<!--设置响应编码-->
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
<!--配置HiddenHttpMethodFilter-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置SpringMVC前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3 配置springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--开启组件扫描-->
<context:component-scan base-package="com.zzy"></context:component-scan>
<!--配置视图解析器-->
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="order" value="1"></property>
<property name="characterEncoding" value="UTF-8"></property>
<property name="templateEngine">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver">
<bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<!--视图前缀-->
<property name="prefix" value="/WEB-INF/templates/"/>
<!--视图后缀-->
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8"/>
</bean>
</property>
</bean>
</property>
</bean>
<!--配置视图控制器 需要配合注解驱动的配置使用-->
<mvc:view-controller path="/" view-name="index"></mvc:view-controller>
<mvc:view-controller path="/toAdd" view-name="empAdd"></mvc:view-controller>
<!--开放静态资源的访问-->
<mvc:default-servlet-handler/>
<!--开启MVC的注解驱动-->
<mvc:annotation-driven/>
</beans>
4 创建实体类Emp
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Emp {
private Integer id;
private String lastName;
private String email;
private Integer gender; //1 male 0 female
}
5 创建EmpDao
@Repository
public class EmpDao {
private static Map<Integer, Emp> emps = null;
static {
emps = new HashMap<Integer, Emp>();
emps.put(1001,new Emp(1001, "AA", "AA@qqq.com", 1));
emps.put(1002,new Emp(1002, "BB", "BB@qqq.com", 0));
emps.put(1003,new Emp(1003, "CC", "CC@qqq.com", 1));
emps.put(1004,new Emp(1004, "DD", "DD@qqq.com", 0));
emps.put(1005,new Emp(1005, "EE", "EE@qqq.com", 1));
}
private static Integer initId = 1006;
public void save(Emp emp){
if (emp.getId()==null){
emp.setId(initId++);
}
emps.put(emp.getId(), emp);
}
public Collection<Emp> getAll(){
return emps.values();
}
public Emp get(Integer id){
return emps.get(id);
}
public void delete(Integer id){
emps.remove(id);
}
}
8.2 功能清单
| 高性能 | URL地址 | 请求方式 |
|---|---|---|
| 访问首页 | / | GET |
| 查询全部数据 | /getAllEmp | GET |
| 删除 | /deleteEmp/2 | DELETE |
| 跳转到添加数据页面 | /toAdd | GET |
| 执行保存 | /save | POST |
| 跳转到更新数据页面 | /updateEmp/2 | GET |
| 执行更新 | /toUpdate | PUT |
8.3 具体功能,访问首页
1 首页
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>首页</h1>
<a th:href="@{/getAllEmp}">查询员工所有信息</a>
</body>
</html>
2 员工列表页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>emp_list</title>
</head>
<body>
<table id="dataTable" border="1" cellspacing="0" th:cellpadding="0" style="text-align: center">
<tr>
<th colspan="5">员工信息</th>
</tr>
<tr>
<th>id</th>
<th>lastName</th>
<th>email</th>
<th>gender</th>
<th>options</th>
</tr>
<tr th:each="emp : ${empList}">
<td th:text="${emp.id}"></td>
<td th:text="${emp.lastName}"></td>
<td th:text="${emp.email}"></td>
<td th:text="${emp.gender}"></td>
<td>
<!--<a th:href="@{/deleteEmp/}+${emp.id}">delete</a>-->
<a @click="deleteEmpClick" th:href="@{'/deleteEmp/'+${emp.id}}">delete</a>
<a th:href="@{'/updateEmp/'+${emp.id}}">update</a>
<a th:href="@{/toAdd}">add</a>
</td>
</tr>
</table>
<form id="deleteFrom" method="post">
<!--RESTFul的delete和put请求需要借助隐藏类型的post请求-->
<input type="hidden" name="_method" value="delete">
</form>
<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
<script type="text/javascript">
var vue = new Vue({
el:"#dataTable",
methods:{
deleteEmpClick:function (event) {
//获取dom对象
var deleteFrom = document.getElementById("deleteFrom");
//获取超链接的href属性赋值给form表单的action
deleteFrom.action = event.target.href;
//提交表单
deleteFrom.submit();
//取消超链接的默认行为
event.preventDefault();
}
}
});
</script>
</body>
</html>
3 添加表单
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>emp_add</title>
</head>
<body>
<form th:action="@{/save}" method="post">
lastName:<input type="text" name="lastName"><br>
email:<input type="text" name="email"><br>
gender:<input type="radio" name="gender" value="1">male
<input type="radio" name="gender" value="0">female<br>
提交:<input type="submit" name="add添加"><br>
</form>
</body>
</html>
3 修改表单
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>emp_update</title>
</head>
<body>
<form th:action="@{/toUpdate}" method="post">
<input type="hidden" name="_method" value="put">
<input type="text" name="id" th:value="${emp.id}"><br>
lastName:<input type="text" name="lastName" th:value="${emp.lastName}"><br>
email:<input type="text" name="email" th:value="${emp.email}"><br>
gender:<input type="radio" name="gender" value="1" th:field="${emp.gender}">male
<input type="radio" name="gender" value="0" th:field="${emp.gender}">female<br>
提交:<input type="submit" name="update"><br>
</form>
</body>
</html>
5 编辑controller
/**
* 测试RESTFul的增删改查
*/
@Controller
public class EmpController {
@Autowired
private EmpDao empDao;
//1 查询所有员工信息
@GetMapping(value = "/getAllEmp")
public String getAllEmp(Model model){
Collection<Emp> empList = empDao.getAll();
System.out.println(empList);
model.addAttribute("empList",empList);
return "empList";
}
//2 删除员工信息
@DeleteMapping(value = "/deleteEmp/{id}")
public String deleteEmp(@PathVariable("id") Integer id){
empDao.delete(id);
return "redirect:/getAllEmp";
}
//3 添加员工信息
@PostMapping(value = "/save")
public String addEmp(Emp emp){
empDao.save(emp);
return "redirect:/getAllEmp";
}
//4 执行修改先查询
@GetMapping(value = "/updateEmp/{id}")
public String uodateEmpById(@PathVariable("id") Integer id,Model model){
Emp emp = empDao.get(id);
model.addAttribute("emp", emp);
return "empUpdate";
}
//5 查询数据做修改后提交修改数据
@PutMapping(value = "/toUpdate")
public String toUpdate(Emp emp){
empDao.save(emp);
return "redirect:/getAllEmp";
}
}
页面展示:
1 列表:
2 添加跳转表单:
3 修改回显表单:
第九章 HttpMessageConverter
HttpMessageConverter:报文信息转换器
作用:将请求报文转换为Java对象,将Java对象转换为响应报文
HttpMessageConverter 提供了两个注解和两个类型:
@RequestBody @ResponseBody
RequestEntity ResponseEntity
9.1 @RequestBody
@RequestBody 可以获取请求体,需要在控制器方法设置一个形参,
使用@RequestBody注解进行标识,
当前请求的请求体将会为当前注解所标识的形参赋值
<form th:action="@{/testRequestBody}" method="post">
<input type="text" name="username"><br>
<input type="password" name="password"><br>
<input type="submit" value="测试@RequestBody注解">
</form>
/*
测试@RequestBody注解获取请求体
*/
@RequestMapping(value = "/testRequestBody",method = RequestMethod.POST)
public String testRequestBody(@RequestBody String requestBody){
System.out.println("requestBody: "+requestBody);
return "success";
}
9.2 RequestEntity
RequestEntity 封装请求报文的的一种类型,
需要在控制器方法的形参中设置该类型的对象,
当前请求的请求报文就会赋值给该形参
可以通过getHeaders()获取请求头信息
通过getBody()获取请求体信息
<form th:action="@{/testRequestEntity}" method="post">
<input type="text" name="username"><br>
<input type="password" name="password"><br>
<input type="submit" value="测试RequestEntity">
</form>
/*
测试RequestEntity获取请求报文信息
*/
@RequestMapping(value = "/testRequestEntity",method = RequestMethod.POST)
public String testRequestEntity(RequestEntity<String> requestEntity){
//获取请求头信息
HttpHeaders headers = requestEntity.getHeaders();
System.out.println("请求头信息: "+headers);
String body = requestEntity.getBody();
System.out.println("请求体信息:"+body);
return "success";
}
请求头信息:
[
host:"localhost:8083",
user-agent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0",
accept:"text/html,application/xhtml+xml,
application/xml;q=0.9,
image/avif,image/webp,*/*;q=0.8",
accept-language:"zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
accept-encoding:"gzip, deflate",
content-type:"application/x-www-form-urlencoded",
content-length:"29",
origin:"http://localhost:8083",
connection:"keep-alive",
referer:"http://localhost:8083/springmvc/",
cookie:"JSESSIONID=26EE2A01DB40ECD495EA1B5CFE32261F; tma=111872281.95305143.1650420094796.1650420094796.1650420094796.1; tmd=48.111872281.95305143.1650420094796.; fingerprint=1e770786a4de04d43889bc8d971a2fb8",
upgrade-insecure-requests:"1",
sec-fetch-dest:"document",
sec-fetch-mode:"navigate",
sec-fetch-site:"same-origin",
sec-fetch-user:"?1"
]
请求体信息:username=admin&password=admin
9.3 @ResponseBody
@ResponseBody 用于标识一个控制器方法
可以将该方法的返回值直接作为响应报文的响应体响应到浏览器
方式一:
通过servletAPI测试response对象来响应浏览器数据
<a th:href="@{/testResponse}">通过servletAPI测试response对象来响应浏览器数据</a>
/*
通过servletAPI测试response对象来响应浏览器数据
*/
@RequestMapping(value = "/testResponse")
public void testResponse(HttpServletResponse response) throws IOException {
response.getWriter().println("hello ,response");
}
方式二、
通过@ResponseBody注解来响应浏览器数据
<a th:href="@{/testResponseBody}">通过@ResponseBody注解来响应浏览器数据</a><br>
/*
通过@ResponseBody注解来响应浏览器数据
*/
@RequestMapping(value = "/testResponseBody")
@ResponseBody
public String testResponseBody(){
return "hello ResponseBody";
}
9.4 @ResponseBody处理Json
@ResponseBody处理Json的步骤:
1 导入jackson依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
2 早SpringMVC的核心配置文件中开启注解驱动,
此时会在HandlerAdaptor中会自动装配一个消息转换器MappingJackson2HttpMessageConverter
可以将响应到浏览器的Java对象转换为Json格式的字符串
3 在处理器方法上使用@ResponseBody进行标识
4 将Java对象直接作为控制器方法的返回值返回,
就会自动换换位json格式的字符串 不是json对象,是json字符串
5 控制器方法
/*
通过@ResponseBody注解来响应对象到浏览器
*/
@RequestMapping(value = "/testResponseBodyObj")
@ResponseBody
public User testResponse(){
User user = new User(111, "AAA", "123", 22, "男");
return user;
}
6 页面展示
{"id":111,"username":"AAA","password":"123","age":22,"ses":"男"}
9.5 处理Ajax
1 请求超链接
<div id="app">
<a @click="testAxios" th:href="@{/testAjax}">测试SpringMVC处理Ajax</a>
</div>
2 通过vue和axios处理点击事件
<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
<script type="text/javascript" th:src="@{/static/js/axios.min.js}"></script>
<script type="text/javascript">
new Vue({
el:"#app",
methods:{
testAxios:function (event) {
axios({
method:"post",
url:event.target.href,
params:{
username:"admin",
password:"123456"
}
}).then(function (result) {
alert(result.data);
});
event.preventDefault();
}
}
});
</script>
/*
测试axios
*/
@RequestMapping(value = "/testAjax")
@ResponseBody
public String testAjax(String username,String password){
System.out.println(username);
System.out.println(password);
return "hello axios";
}
9.6 @RestController注解
@RestController是SpringMVC提供的一复合注解
标识在控制器的类上,就相当于为类添加了@Controller注解,
并且为其中的每个方法添加了@ResponseBody注解
9.7 ResponseEntity
ResponseEntity用于控制器方法的返回值类型,
该控制器方法的返回值就是响应到浏览器的响应报文
第十章 文件上传和下载
10.1 文件上传
文件上传要求form表单的提交方式必须是post,
并且添加属性enctype = “multipart/form-data”.
springMVC中将上传的文件封装到MultipartFile对象中,
通过此文件可以获取文件的相关信息
添加文件上传的依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
在SpringMVC核心配置文件中添加配置信息
<!--配置文件上传使用解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 指定字符集为utf-8 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 设置延时解析文件 -->
<property name="resolveLazily" value="true"/>
</bean>
编写file.html中文件上传代码 ,
enctype额类型必须是: "multipart/form-data"
input类型必须是:"file"
<form th:action="@{/testUp}" method="post" enctype="multipart/form-data">
头像:<input type="file" name="photo"><br>
<input type="submit" value="上传">
</form>
编写文件上传的代码
/*
2 文件上传功能 解决相同文件重复上传文件名相同的问题
*/
@RequestMapping(value = "/testUp",method = RequestMethod.POST)
public String testUp(MultipartFile photo,HttpSession session) throws Exception {
//获取文件的原始文件名
String originalFilename = photo.getOriginalFilename();
//获取上传文件全名的后缀名
String suffixOriginalFilename = originalFilename.substring(originalFilename.lastIndexOf("."));
//通过uuid作为文件的前缀名
String uuid = UUID.randomUUID().toString();
//拼接uuid和suffixOriginalFilename成为上传文件的新的全名称
originalFilename = uuid+suffixOriginalFilename;
//获取服务器的上下文路径
ServletContext servletContext = session.getServletContext();
//通过servletContext获取服务器中photo文件夹的路径
String photoPath = servletContext.getRealPath("photo");
//判断photo目录是否存在
File file = new File(photoPath);
//判断photoPath对镜的路径是否存在
if(!file.exists()){
//如果不存在,在创建文件夹
file.mkdir();
}
//文件上传的最终路径
String finalPath = photoPath+File.separator+originalFilename;
//上传到的位置
photo.transferTo(new File(finalPath));
return "success";
}
执行上传
查看上传之后的图片
10.2 文件下载
编写文件下载页面
<a th:href="@{/testDown}">下载1.jpg文件</a>
编写代码:
/*
1 文件下载下载功能
*/
@RequestMapping(value = "/testDown")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
//获取ServletContext对象
ServletContext servletContext = session.getServletContext();
//通过ServletContext获取服务器中photo文件的真实路径
String realPath = servletContext.getRealPath("/static/img/1.jpg");
System.out.println(realPath);
//创建输入流
InputStream inputStream = new FileInputStream(realPath);
//创建字节数组
//InputStream.available()方法,这个方法可以在读写操作前先得知数据流里有多少个字节可以读取
byte[] bytes = new byte[inputStream.available()];
//将流读取到字节数组中
inputStream.read(bytes);
//创建HttpHeaders对象设置响应头数据
MultiValueMap<String,String> headers = new HttpHeaders();
//设置要下载方式以及下载文件的名字
headers.add("Content-Disposition", "attachment;filename=1.jpg");
//设置响应状态码
HttpStatus statusCode = HttpStatus.OK;
//创建ResponseEntity对象
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes,headers,statusCode);
//关闭输入流
inputStream.close();
return responseEntity;
}
查看文件下载
第十一章 拦截器
11.1 拦截器的配置
SpringMVC中的拦截器用于拦截控制器方法的执行
SpringMVC中的拦截器需要实现HandlerInterceptor
SpringMVC中的拦截器必须在SpringMVC的配置文件中进行配置
核心配置文件中配置:
以下配置方式可以通过ref或bean标签设置拦截器
通过mvc:mapping设置需要拦截的请求,
通过mvc:exclude-mapping设置需要排除的请求,即需要放行的请求
其中:
对所有路径进行拦截
/*表示拦截上下文路径下的一层目录的请求,
/**表示拦截多层目录的请求
<!--配置拦截器-->
<bean class="com.zzy.controller.FirstInterceptor"></bean>
<ref bean="firstInterceptor"></ref>
以上两种配置方式都是对DispatcherServlet所处理的所有请求进行拦截
<mvc:interceptors>
<mvc:interceptor>
<!--放行 /** 表示拦截多层目录的请求-->
<mvc:mapping path="/**"/>
<!--放行 / 主页面请求-->
<mvc:exclude-mapping path="/"/>
<ref bean="firstInterceptor"></ref>
</mvc:interceptor>
</mvc:interceptors>
编写自定义拦截器
/**
* 自定义拦截器
*/
@Component
public class FirstInterceptor implements HandlerInterceptor {
//在控制器方法执行之前执行
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("第一个拦截器的pre方法执行--在控制器方法执行之前执行");
return true; //false表示拦截,true表示放行
}
//在控制器方法之后执行
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("第一个拦截器的post方法执行---在控制器方法执行之后执行");
}
//在视图渲染之后执行
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("第一个拦截器的afterComp方法执行--在视图渲染之后执行");
}
}
11.2 拦截器的三个抽象方法
SpringMVC中的拦截器有三个抽象方法:
1 preHandle:
控制器方法执行之前执行preHandle(),
其boolean类型的返回值表示是否拦截或者放行,
返回true为放行,即调用控制器方法
返回false表示拦截,即不调用控制器方法
2 postHandle:
在控制器方法执行之后执行postHandle()
3 afterComplation:
处理完视图和模型数据即渲染完视图,
之后执行afterComplation()
11.3 多个拦截器的执行顺序
1 若每个拦截器preHandle()都返回true
此时多个拦截器的执行顺序,
与拦截器在SpringMVC的配置文件中的配置顺序有关
preHandle()会按照配置的顺序执行,
而postHandle()和afterComplation()会按照配置的反序执行
2 若某个拦截器的preHandle()返回了false
preHandle()返回false和之前的拦截器的preHandle()都执行
postHandle()不会执行,
返回false的拦截器之前的afterComplation()会执行
第十二章 异常处理
12.1 基于配置的异常处理
SpringMVC提供了一个处理控制器方法执行过程中出现的异常的接口:
HandlerExceptionResolver。
HandlerExceptionResolver接口的实现类有:
-- DefaultHandlerExceptionResolver
-- SimpleMappingExceptionResolver
SpringMVC提供了自定义的异常处理器
SimpleMappingExceptionResolver,使用方式如下
<!--配置异常处理器-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<!--
properties的键表示处理器方法在执行过程中出现的异常的类型
properties的键表示若出现指定异常时,设置一个新的视图名称,从而跳转到指定页面
error表示发生异常后,跳转的指定页面
-->
<props>
<prop key="java.lang.ArithmeticException">error</prop>
</props>
</property>
<!--设置将异常信息共享在请求域中的键-->
<property name="exceptionAttribute" value="exception"></property>
</bean>
12.2 注解方式配置异常处理器
/**
* 使用异常处理器注解注解
*/
@ControllerAdvice
public class AnnoExceptionHandler {
@ExceptionHandler(value = {ArithmeticException.class,NullPointerException.class})
public String testAnnoExceptionHandler(Exception ex, Model model){
model.addAttribute("exception", ex);
return "error";
}
}
第十三章 注解配置SpringMVC
使用配置类和注解代替web.xml和SpringMVC配置文件的功能
13.1 创建初始化类,代替web.xml
在servlet环境中,容器会在类路径中查找实现
javax.servlet.ServletContainerInitializer接口的类,
如果找到的话就用它来配置Servlet容器
Spring提供了这个接口的实现名为
SpringServletContainerInitializer,
这个类又会反过来查找实现WebApplicationInitializer的类,
并将配置的任务交给衙门来完成,
Spring引入一个便利的WebApplicationInitializer基础实现名为
AbstractAnnotationConfigDispatcherServletInitializer,
当我们的类扩展了AbstractAnnotationConfigDispatcherServletInitializer并将其部署到Servlet容器的时候,容器会自动发现它,并用它来配置Servlet上下文。
/**
* web工程的初始化类,用来代替web.xml
*/
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
/*
指定Spring的配置类
*/
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
/*
指定SpringMVC的配置类
*/
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMVCConfig.class};
}
/*
指定DispatcherServlet的映射规则,即url-pattern
*/
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
/*
注册配置过滤器
*/
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceRequestEncoding(true);
HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
return new Filter[]{characterEncodingFilter,hiddenHttpMethodFilter};
}
13.2 创建SpringConfig配置类代替spring的核心配置文件
/**
* Spring的配置类
*/
@Configuration
public class SpringConfig {
}
13.3 创建SpringMVCConfig配置类代替SpringMVC的核心配置文件
/**
* SpringMVC的配置类,代替其核心配置文件,其核心组件包括如下:
* 1 mvc注解驱动:mvc:annotation-driven
* 2 组件扫描:context:component-scan
* 3 文件上传解析器:CommonsMultipartResolver
* 6 拦截器:mvc:interceptors
* 5 配置视图控制器 view-controller
* 4 异常处理器:SimpleMappingExceptionResolver
* 7 静态资源处理 mvc:default-servlet-handler
* 8 视图解析器:ThymeleafViewResolver
*/
//将当前类标识为一个配置类
@Configuration
//1 开启MVC的注解驱动
@EnableWebMvc
//2 开启组件扫描
@ComponentScan(basePackages = "com.zzy.controller")
public class SpringMVCConfig implements WebMvcConfigurer {
// 3 文件上传解析器:CommonsMultipartResolver
@Bean
public MultipartResolver multipartResolver(){
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
return commonsMultipartResolver;
}
// 4 异常处理器:SimpleMappingExceptionResolver
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
SimpleMappingExceptionResolver simpleMappingExceptionResolver = new SimpleMappingExceptionResolver();
Properties properties = new Properties();
properties.setProperty("java.lang.ArithmeticException","error");
simpleMappingExceptionResolver.setExceptionMappings(properties);
//设置异常信息到域对象中
simpleMappingExceptionResolver.setExceptionAttribute("exception");
resolvers.add(simpleMappingExceptionResolver);
}
// 5 配置视图控制器 view-controller
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//设置视图控制器对应的路径
ViewControllerRegistration viewControllerRegistration = registry.addViewController("/hello");
//设置视图控制器对应的视图名称
viewControllerRegistration.setViewName("hello");
}
// 6 拦截器:mvc:interceptors
@Override
public void addInterceptors(InterceptorRegistry registry) {
//创建一个拦截器对象
TestInterceptor testInterceptor = new TestInterceptor();
InterceptorRegistration interceptorRegistration = registry.addInterceptor(testInterceptor);
//添加拦截路径,对所有路径进行拦截,多层目录
interceptorRegistration.addPathPatterns("/**");
//添加放行路径,首页路径进行放行
//interceptorRegistration.excludePathPatterns("/");
}
//7 静态资源处理 mvc:default-servlet-handler
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
//8 视图解析器
//配置生成模板解析器
@Bean
public ITemplateResolver templateResolver(){
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(webApplicationContext.getServletContext());
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setTemplateMode(TemplateMode.HTML);
return templateResolver;
}
//生成模板引擎并为模板引擎注入模板解析器
@Bean
public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver){
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
return templateEngine;
}
//生成视图解析器并为其注入模板引擎
@Bean
public ViewResolver viewResolver(SpringTemplateEngine templateEngine){
ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver();
thymeleafViewResolver.setCharacterEncoding("UTF-8");
thymeleafViewResolver.setTemplateEngine(templateEngine);
return thymeleafViewResolver;
}
}
第十四章 SpringMVC的执行流程
14.1 SpringMVC常用组件
1 DispatcherServlet 前端控制器
不需要工程师开发,由框架提供
作用:统一处理请求和响应,
整个流程控制的中心,
由它调用其它组件来处理用户的请求
2 HandlerMapping 处理器映射器
不需要工程师开发,由框架提供
作用:根据请求的url,method等信息查找handler,
即控制器方法
3 Handler 处理器
需要工程师开发
作用:在DispatcherServlet的控制下,
Handler对具体的用户请求进行处理
4 HandlerAdapter 处理器适配器
不需要工程师开发,由框架提供
作用:通过HandlerAdapter对处理器,即控制器方法进行执行
5 ViewResolver 视图解析器
不需要工程师开发,由框架提供
作用:进行视图解析,得到相应的视图,
如:ThymeleafViewResolver 模板视图解析器
InternalResourceView 转发视图解析器
RedirectView 重定向视图解析器
6 View 视图
不需要工程师开发,由框架或者视图技术提供
作用:将模型数据通过页面展示给用户
14.2 DispatcherServlet的执行流程
1 用户向服务器发送请求,
请求被SpringMVC的前端控制器DispatcherServlet获取
2 DispatcherServlet对请求URL进行解析,
得到请求资源标识符URI,判断请求URI对应的映射
不存在:再判断是否配置了mvc:default-servlet-handler
如果没有配置,则控制台报错映射差找不到,客户端404错误
如果有配置,则访问目标资源一般是静态资源:js/css/html
找不到客户端也会展示404错误
存在则执行以下流程
3 根据该URL,
调用HandlerMapping获取该Handler配置的所有相关对象,
包括Handler对象以及Handler对应的拦截器。
最后以HandlerExecutionChain执行链对象的形式返回
4 DispatcherServlet根据获得的Handler,
选择一个合适的HandlerAdapter
5 如果成功获得HandlerAdapter,
此时将开始执行拦截器的preHandler(...)方法(正向)
6 提取Request中的模型数据,填充Handler入参,
开始执行Handler方法(controller方法),处理请求
在填充Handler的入参过程中,根据配置Spring将会做如下工作:
a、HtppMessageConveter,
将请求消息(json或xml)转换成一个对象,
将对象转换成指定的响应信息
b、数据转换:对请求头信息进行数据转换,如String转换成Integer
c、数据格式化,对请求消息进行数据格式化。
如将字符串换换成格式化数字或者格式化日期等
d、数据验证:验证数据的有效性,如长度,格式,
验证结果存储到BindingResult或error中
7 Handlerz还行完成后,向DispatcherServlet返回一个ModelAndView
8 此时将开始执行拦截器的postHandler(...)方法(逆向)
9 根据返回的ModelAndView,
(但是此时会判断是否发生异常,如果存在异常,
则执行HandlerExceptionResolver进行异常处理)
选择一个合适的ViewResolver进行视图解析
根据Model和View,来渲染视图。
10 渲染视图完毕执行拦截器的afterComplation(...)方法.(逆向)
11 将渲染结果返回给客户端























5951

被折叠的 条评论
为什么被折叠?



