
- 域对象共享数据
- springmvc视图
- RESTFful简介
5、域对象共享数据
- request
- session
- application
5.1、使用ServletAPI向request域对象共享数据
1 2 3 4 5
| @RequestMapping("/testServletAPI") public String testServletAPI(HttpServletRequest request){ request.setAttribute("testScope", "hello,servletAPI"); return "success"; }
|
5.2、使用ModelAndView向request域对象共享数据
- 通过ModelAndView向请求域对象共享数据
如果要使用ModelAndView ,方法的返回值必须是 ModelAndView
前端超链接
1
| <a th:href="@{/test/mav}" >测试通过ModelAndView向请求域共享数据</a>
|
后端控制器
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @RequestMapping("/test/mav") public ModelAndView testMAV(){
ModelAndView modelAndView=new ModelAndView(); modelAndView.addObject("testRequestScope","helloMAV"); modelAndView.setViewName("success"); return modelAndView; }
|
视图页面
1
| <p th:text="${testRequestScope}"/>
|
5.3、使用Model向request域对象共享数据
前端超链接
1
| <a th:href="@{/test/model}" >测试通过model向请求域共享数据</a>
|
后端控制器
1 2 3 4 5 6 7 8
| @RequestMapping("/test/model") public String testMAV(Model model){
model.addAttribute("testRequestScope","helloMode"); return "success"; }
|
5.4、使用ModelMap向request域对象共享数据
前端超链接
1
| <a th:href="@{/test/modelMap}" >测试通过model向请求域共享数据</a>
|
后端控制器
1 2 3 4 5 6 7
| @RequestMapping("/test/modelMap") public String testModelMap(ModelMap modelMap){ modelMap.addAttribute("testRequestScope","helloModelMap"); return "success"; }
|
5.5、使用map向request域对象共享数据
前端超链接
1
| <a th:href="@{/test/map}" >测试通过model向请求域共享数据</a>
|
后端控制器
1 2 3 4 5 6 7
| @RequestMapping("/test/map") public String testMap(Map<String,Object> map){ map.put("testRequestScope","helloMap"); return "success"; }
|
5.6、Model、ModelMap、Map的关系
Model、ModelMap、Map类型的参数其实本质上都是 BindingAwareModelMap 类型的
最终实例化的时候都是BindingAwareModelMap
1 2 3 4 5 6 7
| public interface Model{}
public class ModelMap extends LinkedHashMap<String, Object> {}
public class ExtendedModelMap extends ModelMap implements Model {}
public class BindingAwareModelMap extends ExtendedModelMap {}
|
5.7、向session域共享数据
会话:一次浏览器开启到浏览器关闭的过程
- 直接用servletAPI即可,SpringMVC的方式麻烦
前端超链接
1
| <a th:href="@{/test/session}" >测试向会话域共享数据</a>
|
后端控制器
1 2 3 4 5 6 7
| @RequestMapping("/test/session") public String testSession(HttpSession session){ session.setAttribute("testSessionScope", "hello,session"); return "success"; }
|
视图页面
1
| <p th:text="${session.testRequestScope}"/>
|
- 开启这个选项,保证即使服务器重启,仍然会报错session中的数据
Session 的钝化与活化
1>钝化
- 钝化其实是序列化的过程,因此如果session中存储的数据是一个实体类,那么这个实体类需要实现
serializable接口
当服务器正常关闭时,还存活着的session(在设置时间内没有销毁) 会随着服务器的关闭被以文件(“SESSIONS.ser”)的形式存储在tomcat 的work 目录下,这个过程叫做Session 的钝化。
2>活化
当服务器再次正常开启时,服务器会找到之前的“SESSIONS.ser” 文件,从中恢复之前保存起来的Session 对象,这个过程叫做Session的活化。
3>注意事项
- 想要随着Session 被钝化、活化的对象它的类必须实现Serializable 接口,还有要注意的是只有在服务器正常关闭的条件下,还未超时的Session 才会被钝化成文件。当Session 超时、调用invalidate 方法或者服务器在非正常情况下关闭时,Session 都不会被钝化,因此也就不存在活化。
- 在被钝化成“SESSIONS.ser” 文件时,不会因为超过Session 过期时间而消失,这个文件会一直存在,等到下一次服务器开启时消失。
- 当多个Session 被钝化时,这些被钝化的Session 都被保存在一个文件中,并不会为每个Session 都建立一个文件。

5.8、向application域共享数据
前端超链接
1
| <a th:href="@{/test/application}" >测试向应用域共享数据</a>
|
后端控制器
1 2 3 4 5 6
| @RequestMapping("/test/application") public String testApplication(HttpSession session){ ServletContext servletContext= session.getServletContext(); servletContext.setAttribute("testApplication","hello Application"); return "success"; }
|
视图页面
1
| <p th:text="${application.testApplicationScope}"/>
|
6、SpringMVC的视图
- SpringMVC中的视图是View接口,视图的作用渲染数据,将模型Model中的数据展示给用户
SpringMVC视图的种类很多,默认有转发视图和重定向视图
当工程引入jstl的依赖,转发视图会自动转换为JstlView(jsp)
若使用的视图技术为Thymeleaf,在SpringMVC的配置文件中配置了Thymeleaf的视图解析器,由此视图解析器解析之后所得到的是ThymeleafView
WEB-INF目录下的springMVC-servlet.xml 配置文件

org.thymeleaf.spring5.view.ThymeleafViewResolver
6.1、ThymeleafView
当控制器方法中所设置的视图名称没有任何前缀时,此时的视图名称会被SpringMVC配置文件中所配置的视图解析器(org.thymeleaf.spring5.view.ThymeleafViewResolver)解析,视图名称拼接视图前缀和视图
后缀所得到的最终路径,会通过转发的方式实现跳转
超链接
1
| <a th:href="@{/test/view/thymeleaf}">测试SpringMVC 的视图</a>
|
1 2 3 4 5 6 7
| @Controller public class TestViewController { @RequestMapping("/test/view/thymeleaf") public String testThymeleaf(){ return "success"; } }
|

success会被 解析为配置文件中的前缀 、后缀 -->/WEB-INF/templates/success.html
6.2、转发视图
SpringMVC中默认的转发视图是InternalResourceView
- 只能实现简单的转发,如果使用thymeleaf作为视图渲染技术,thymeleaf将不会渲染页面
SpringMVC中创建转发视图的情况:
当控制器方法中所设置的视图名称以"forward:"为前缀时,创建InternalResourceView视图,此时的视图名称不会被
SpringMVC配置文件中所配置的视图解析器解析,而是会将前缀"forward:"去掉,剩余部分作为最终路径通过转发的方式实现跳转
例如"forward:/",“forward:/employee”
超链接
1
| <a th:href="@{/test/view/forward}">测试SpringMVC 的视图</a>
|
controller
1 2 3 4 5 6 7 8
| @Controller public class TestViewController { @RequestMapping("/test/view/forward") public String testThymeleaf(){ return "forward:/test/view/thymeleaf";
} }
|

6.3、重定向视图
SpringMVC中默认的重定向视图是RedirectView
当控制器方法中所设置的视图名称以"redirect:"为前缀时,创建RedirectView视图,此时的视图名称不会被SpringMVC配置文件中所配置的视图解析器解析,而是会将前缀"redirect:"去掉,剩余部分作为最终路径通过重定向的方式实现跳转
例如 “redirect:/”,“redirect:/employee”
超链接
1
| <a th:href="@{/test/view/redirect}">测试SpringMVC 的视图</a>
|
controller
1 2 3 4 5 6 7 8 9
| @Controller public class TestViewController { @RequestMapping("/test/view/redirect") public String testThymeleaf(){ return "forward:/test/view/thymeleaf"; } }
|
thymeleaf: ThymeleafView +RedirectView
jsp: InternalResourceView+RedirectView
6.4、视图控制器view-controller

当控制器方法中,仅仅用来实现页面跳转,即只需要设置视图名称时,可以将处理器方法使用viewcontroller标签进行表示
- 视图控制器:为当前的请求直接设置视图名称实现页面跳转
若设置视图控制器,则只有视图控制器所设置的请求会被处理 ,其他的请求将会全部404
此时必须再配置一个标签:
<mvc:annotation-driven> :开启mvc注解驱动
1 2
| <mvc:view-controller path="/testView" view-name="index"></mvc:view-controller>
|
效果如下:
配置文件:
springMVC.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| <?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:mvc="http://www.springframework.org/schema/mvc" 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/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="pers.dhx_.controller"/> <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver"> <property name="order" value="1"/> <property name="characterEncoding" value="UTF-8"/> <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:default-servlet-handler/> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="defaultCharset" value="UTF-8" /> <property name="supportedMediaTypes"> <list> <value>text/html</value> <value>application/json</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <mvc:view-controller path="/testView" view-name="index"/> </beans>
|
注:
当SpringMVC中设置任何一个view-controller时,其他控制器中的请求映射将全部失效,此时需
要在SpringMVC的核心配置文件中设置开启mvc注解驱动的标签:
<mvc:annotation-driven />
7、RESTful
7.1、RESTful简介
- REST:Representational State Transfer,表现层资源状态转移。
1>资源
资源是一种看待服务器的方式,即,将服务器看作是由很多离散的资源组成。每个资源是服务器上一个
可命名的抽象概念。因为资源是一个抽象的概念,所以它不仅仅能代表服务器文件系统中的一个文件、
数据库中的一张表等等具体的东西,可以将资源设计的要多抽象有多抽象,只要想象力允许而且客户端
应用开发者能够理解。与面向对象设计类似,资源是以名词为核心来组织的,首先关注的是名词。一个
资源可以由一个或多个URI来标识。URI既是资源的名称,也是资源在Web上的地址。对某个资源感兴
趣的客户端应用,可以通过资源的URI与其进行交互。
2>资源的表述
资源的表述是一段对于资源在某个特定时刻的状态的描述。可以在客户端-服务器端之间转移(交换)。
资源的表述可以有多种格式,例如HTML/XML/JSON/纯文本/图片/视频/音频等等。资源的表述格式可以通过协商机制来确定。
请求-响应方向的表述通常使用不同的格式。
3>状态转移
状态转移说的是:在客户端和服务器端之间转移(transfer)代表资源状态的表述。通过转移和操作资源的表述,来间接实现操作资源的目的。
7.2、RESTful的实现
具体说,就是 HTTP 协议里面,四个表示操作方
式的动词:GET、POST、PUT、DELETE。
它们分别对应四种基本操作:
- GET 用来获取资源
- POST 用来新建资源
- PUT 用来更新资源
- DELETE用来删除资源
REST 风格提倡 URL 地址使用统一的风格设计,从前到后各个单词使用斜杠分开,不使用问号键值对方式携带请求参数,
而是将要发送给服务器的数据作为 URL 地址的一部分,以保证整体风格的一致性。
| 操作 |
传统方式 |
REST风格 |
| 查询操作 |
getUserById?id=1 |
user/1–>get请求方式 |
| 保存操作 |
saveUser |
user–>post请求方式 |
| 删除操作 |
deleteUser?id=1 |
user/1–>delete请求方式 |
| 更新操作 |
updateUser |
user–>put请求方式 |
7.3、HiddenHttpMethodFilter简介
- 由于浏览器只支持发送get和post方式的请求,我们在需要发送put和delete请求时就会用到
HiddenHttpMethodFilter过滤器
SpringMVC 提供了 HiddenHttpMethodFilter 帮助我们将 POST 请求转换为 DELETE 或 PUT 请求
HiddenHttpMethodFilter 处理put和delete请求的条件:
- 当前请求的请求方式必须为post
- 当前请求必须传输请求参数_method
具体使用如下:
1 2 3 4 5 6 7 8 9
| <form method="post" th:action="@{/user}"> <input th:type="hidden" name="_method" value="PUT"> <input th:type="submit" value="修改用户信息"> </form>
<form method="post" th:action="@{/user/1}"> <input th:type="hidden" name="_method" value="DELETE"> <input th:type="submit" value="删除用户信息"> </form>
|
满足以上条件,HiddenHttpMethodFilter 过滤器就会将当前请求的请求方式转换为请求参数
method的值,因此请求参数method的值才是最终的请求方式
7.4、简单发送请求Demo
1>创建maven工程(此处是添加模块)
pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <packaging>war</packaging> <groupId>org.example</groupId> <artifactId>demo01</artifactId> <version>1.0-SNAPSHOT</version> <dependencies>
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.1</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.12.RELEASE</version> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.12.RELEASE</version> <scope>compile</scope> </dependency> </dependencies>
<properties> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties>
</project>
|
2>添加web模块

配置web.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| <?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>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name> CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
<servlet> <servlet-name>SpringMVC</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>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
|
3>配置springmvc配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| <?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:mvc="http://www.springframework.org/schema/mvc" 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/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="pers.dhx_.controller"/> <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver"> <property name="order" value="1"/> <property name="characterEncoding" value="UTF-8"/> <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:default-servlet-handler/> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="defaultCharset" value="UTF-8" /> <property name="supportedMediaTypes"> <list> <value>text/html</value> <value>application/json</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
<mvc:view-controller path="/" view-name="index"/> </beans>
|
4>添加相关文件
- controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package pers.dhx_.controller;
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;
@Controller public class RestfulTest { }
|
- 前端发送请求
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <h1>index.html</h1>
<a th:href="@{/user}">查询所有的用户信息</a> <br/><br/> <a th:href="@{/user/1}">根据id查询所有的用户信息</a><br/><br/> <form method="post" th:action="@{/user}"> <input th:type="submit" value="添加用户信息"> </form><br/><br/>
<form method="post" th:action="@{/user}"> <input th:type="hidden" name="_method" value="PUT"> <input th:type="submit" value="修改用户信息"> </form><br/><br/>
<form method="post" th:action="@{/user/1}"> <input th:type="hidden" name="_method" value="DELETE"> <input th:type="submit" value="删除用户信息"> </form><br/><br/>
</body> </html>
|
- success.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>success</title> </head> <body> <h1>success.html</h1> <h1>success.html</h1> <h1>success.html</h1> <h1>success.html</h1> <h1>success.html</h1> <h1>success.html</h1> </body> </html>
|
5>添加HiddenHttpMethodFilter过滤器
- 注意:编码过滤器
CharacterEncodingFilter必须卸载所有过滤器的最前面,否则可能会出现乱码情况
由于原本的请求方式只有GET以及POST ,为了发送PUT 以及DELETE请求,需要在web.xml 文件中配置HiddenHttpMethodFilter过滤器
1 2 3 4 5 6 7 8 9
| <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>
|
模块结构如下:
6>在controller中编写测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| @Controller public class RestfulTest {
@RequestMapping(value="/user",method= RequestMethod.GET) public String getAllUser(){ System.out.println(" * 查询所有的用户信息 : /user --> get"); return "success"; }
@RequestMapping(value="/user/{id}",method= RequestMethod.GET) public String getUserById(@PathVariable("id")Integer id){ System.out.println(" * 根据id查询用户信息 : /user/"+id+" --> get"); return "success"; } @RequestMapping(value="/user",method= RequestMethod.POST) public String insertUser(){ System.out.println(" * 添加用户信息 : /user --> post"); return "success"; }
@RequestMapping(value="/user",method= RequestMethod.PUT) public String updateUser(){ System.out.println(" * 修改用户信息 : /user --> put"); return "success"; }
@RequestMapping(value="/user/{id}",method= RequestMethod.DELETE) public String deleteUser(@PathVariable("id")Integer id){ System.out.println(" * 删除用户 : /user --> delete"); return "success"; } }
|

小插曲:
@RequestMapping(value="/user/{id}",method= RequestMethod.DELETE)可以写成
@DeleteMapping(value="/user/{id}")
其他几个同理
@GetMapping
- @PutMapping
@PostMapping
这样一来可以省略后面的 RequestMethod.*** ,并且效果一样