SpringMVC简介

什么是MVC

MVC是一种软件架构的思想,将软件按照模型、视图、控制器来划分

M:Model,模型层,指工程中的JavaBean,作用是处理数据

JavaBean分为两类:

  • 实体类Bean:专门存储业务数据的,比如 Student,User
  • 原物处理Bean:指 Service 或 Dao 对象,专门用来处理业务逻辑和数据访问

V:View,视图层,指工程中的 jsp 或 jsp 等页面,作用是与用户进行交互,展示数据

C:Controller,控制层,指工程中的servlet,作用是接收请求和响应浏览器

MVC的工作流程:

用户通过试图发送请求到 服务器,在 服务器 中 请求被 Controller 接受, Controller 调用相应的 Model 层处理请求,处理完毕后将结果返回到 Controller,Controller 再根据请求处理的结果 找到相应的 view 视图,渲染数据后,最终响应给 浏览器

MVC是一种软件架构模式,其名称代表“模型-视图-控制器”。下面是MVC的工作流程:

  1. 用户与视图交互:MVC模式的工作流程始于用户与视图之间的交互。视图是用户界面的一部分,它负责展示数据和接收用户输入。

  2. 视图通知控制器:当用户与视图进行交互时,视图将通知控制器。控制器是MVC模式的中央处理器,它负责协调模型和视图之间的交互。

  3. 控制器更新模型:当控制器接收到来自视图的通知时,它将根据用户输入更新模型。模型是MVC模式的数据层,它负责存储数据并定义与数据相关的操作。

  4. 模型通知视图:当模型发生变化时,它将通知视图。视图将根据模型的变化更新用户界面,以反映最新的数据状态。

  5. 用户与更新后的视图交互:用户可以再次与更新后的视图进行交互,并重复上述步骤。这种交互可以包括输入新数据、修改或删除现有数据等操作。

总体来说,MVC的工作流程可以概括为:用户与视图交互,视图通知控制器,控制器更新模型,模型通知视图,用户与更新后的视图交互。这种模式的优势是它可以将应用程序的不同部分分离开来,使得代码更易于维护和重用。

什么是SpringMVC

SpringMVC是Spring的一个后续产品,是Spring的一个子项目

SpringMVC是 Spring 为表述层开发提供的一整套完备的解决方案。在表述层框架历经 Strust、WebWork、Strust2等诸多产品的历代更迭之后,目前业界普遍选择了SpringMVC作为JavaEE项目表述层开发的首选方案。

注:三层架构分为表述层(或表示层)、业务逻辑层、数据访问层、表述层表示前台页面和后台servlet

SpringMVC的特点

  • Spring家族的原生产品,与 IOC 容器等基础设施无缝对接
  • 基于原生的Servlet,通过了功能强大的封装我们请求过程的前端控制器DispatcherServlet,对请求和响应进行统一处理
  • 表述层各细分领域需要解决的问题全方位覆盖,提供全面解决方案
  • 代码清新简洁,大幅度提升开发效率
  • 内部组件化程度高,可插拔式组件即插即用,想要什么功能配置响应组件即可
  • 性能卓著,尤其适合现代大型、超大型互联网项目要求

SpringMVC的使用

引入依赖

pom.xml文件:注意打包方式是 war 包,不是 jar 包

<?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>

    <groupId>com.byxl8112.mvc</groupId>
    <artifactId>springMVC-demo1</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <!-- SpringMVC -->
        <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>

        <!-- ServletAPI -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- Spring5和Thymeleaf整合包 -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.12.RELEASE</version>
        </dependency>

    </dependencies>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

</project>

ServletAPI依赖中:

依赖范围->provided:运行时无效,Tomcat会有servlet-api,但是编译期需要,所以要有这个依赖,要不然无法通过编译。所以它不需要被打包,因为服务器有。

Thymeleaf就是通过视图技术来控制页面中的内容

spring6和Thymeleaf整合包:

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring6</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>

注:由于 Maven 的传递性,我们不必将所有需要的包全部配置依赖,二十配置最顶端的依赖,其他靠传递性导入。

image-20230530105009262

配置web.xml

创建web.xml文件:

image-20230530105137298

在SpringMVC的前端控制器DispatcherServlet

在SpringMVC中,从浏览器发送到服务器的请求,都要被DispatcherServlet前端控制器进行处理

a>默认配置方式

此配置作用下,SpringMVC的配置文件默认位于WEB-INF下,默认名称为<servlet-name>-servlet.xml,例如,以下配置所对应SpringMVC的配置文件位于WEB-INF下,文件名为 springMVC-servlet.xml

web.xml类型配置文件:springMVC-servlet.xml

<!-- 配置SpringMVC的前端控制器,对浏览器发送的请求统一进行处理 -->
<servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <!--
        设置springMVC的核心控制器所能处理的请求的请求路径
        /所匹配的请求可以是/login或.html或.js或.css方式的请求路径
        但是/不能匹配.jsp请求路径的请求
    -->
    <url-pattern>/</url-pattern>
</servlet-mapping>

/不能匹配.jsp请求路径的请求:

如果使用前端控制器来处理了jsp,就会用前端控制器这个Servlet来处理,而不会调用该jsp所对应的Servlet进行处理,而jsp请求,因为jsp本身就是一个Servlet,所以请求jsp时已经有特定的Servlet来处理该请求了(就是它自己),需要用 /* 来处理.jsp请求路径的请求

框架 = 配置文件 + jar 包

b>扩展配置方式

可通过init-param标签设置SpringMVC配置文件的位置和名称,通过 load-on-startup标签设置SpringMVC前端控制器DispatcherServlet的初始化时间

web.xml类型配置文件:spring-mvc-sevlet.xml文件

<!-- 配置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>
    <servlet-name>springMVC</servlet-name>
    <!--
        设置springMVC的核心控制器所能处理的请求的请求路径
        /所匹配的请求可以是/login或.html或.js或.css方式的请求路径
        但是/不能匹配.jsp请求路径的请求
    -->
    <!--能够请求的路径是上下文路径下所有请求路径-->
    <url-pattern>/</url-pattern>
</servlet-mapping>

注:

<url-pattern>标签中使用/和/*的区别:

/所匹配的请求可以是/login或.html或.js或.css方式的请求路径,但是/不能匹配.jsp请求路径的请求

因此就可以避免在访问jsp页面时,该请求被DispatcherServlet处理,从而找不到相应的页面

/*则能够匹配所有请求,例如在使用过滤器时,若需要对所有请求进行过滤,就需要使用/*的写法

<load-on-startup>1<load-on-startup>:当值为0或者大于0时,表示容器在应用启动时就加载这个servlet;当值为一个负数或者没有指定时,则指示容器在该servlet被选择时才加载

浏览器发送的请求要交给前端控制器来处理,前端控制器是一个servlet,要想通过servlet处理请求,需要在web.xml进行注册。

创建请求控制器

由于前端控制器对浏览器发送的请求进行了统一的处理,但是具体的请求有不同的处理过程,因此需要创建处理具体请求的类,即请求控制器

请求控制器中每一个处理请求的方法称为控制器方法

因为SpringMVC的控制器有一个pojo(普通的Java类)担任,因此需要通过@Contrlller 注解将其标识为一个控制层组件,交给Spring的IoC容器管理,此时SpringMVC才能够是被控制器的存在

@Controller
public class HelloController {
    
}

创建SpringMVC的配置文件

resources包下的springMVC.xml文件:

<!-- 自动扫描包 -->
<context:component-scan base-package="com.byxl8112.mvc.controller"/>

<!-- 配置Thymeleaf视图解析器 -->
<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>

<!-- 
   处理静态资源,例如html、js、css、jpg
  若只设置该标签,则只能访问静态资源,其他请求则无法访问
  此时必须设置<mvc:annotation-driven/>解决问题
 -->
<mvc:default-servlet-handler/>

<!-- 开启mvc注解驱动 -->
<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>

WEB-INF下面的内容不能被直接访问,视图前缀和视图后缀用来匹配文件的,比如这里是匹配 /WEB-INF/templates包下的xxx.html文件。

测试HelloWorld

a>实现对首页的访问

在请求控制器中创建处理请求的方法:

com.byxl8112.mvc.controller包下的HelloController.java类

@Controller
public class HelloController {

    // "/"  -->/WEB/templates/index.html

    @RequestMapping("/")
    public String index(){
        //返回视图名称
        return "index";
    }
}

b>通过超链接跳转到指定页面

在主页index.html中设置超链接

webapp\WEB-INF\templates\包下的index.html文件:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>主题</title>
</head>
<body>
    <h1>主题</h1>
    <!--/target指的是绝对路径-->
    <a th:href="@{/target}">访问目标页面target.html</a>
</body>
</html>

其中的xmlns:th="http://www.thymeleaf.org"是指可以使用thymeleaf方法

webapp\WEB-INF\templates\包下的target.html文件:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>目标</title>
</head>
<body>
HelloWord
</body>
</html>

在请求控制器中创建处理请求的方法

@RequestMapping("/target")  
public String toTarget(){
    return "target";
}

这里注解的"/target"其实就是servlet-mapping,就是浏览器访问该资源的一个url映射

注解里不写/target,你点击超链接以后,服务器怎么知道你要走哪个方法,服务器不知道你走哪个方法,自然就进不去目标页面

执行结果:

首页(index.html页面):

image-20230530113142416

访问目标页面(target.html页面):

image-20230530113242527

总结

浏览器发送请求,若请求地址符合前端控制器的url-pattern,该请求就会被前端控制器DispatcherServlet处理。前端控制器会读取SpringMVC的核心配置文件,通过扫描组件找到控制器,将请求地址和控制器中@RequestMapping注解的value属性值进行匹配,若匹配成功,该注解所标识的控制器方法就是处理请求的方法。处理请求的方法需要返回一个字符串类型的视图名称,该视图名称会被视图解析器解析,加上前缀和后缀组成视图的路径,通过Thymeleaf对视图进行渲染,最终转发到视图所对应页面

@RequestMapping注解

@RequestMapping注解的功能

从注解名称上我们可以看到,@RequestingMapping 注解的作用就是将请求和处理请求的控制器方法关联起来,建立映射关系

SpringMVC 收到指定的请求,就会来找到在 映射关系中对应的控制器方法来处理这个请求

@RequestMapping注解的位置

@RequestMapping 标识一个类:设置映射请求的请求路径的初始信息

@RequestMapping 标识一个方法:设置映射请求的请求路径的具体信息

@Controller
@RequestMapping("/test")
public class RequestMappingController {

	//此时请求映射所映射的请求的请求路径为:/test/testRequestMapping
    @RequestMapping("/testRequestMapping")
    public String testRequestMapping(){
        return "success";
    }
}

@RequestMapping注解的value属性

@RequestMapping注解的value属性通过请求的请求地址匹配请求映射

@RequestMapping 注解的value属性是一个字符串类型的数组,表示该请求映射能够匹配多个请求地址所对应的请求

@RequestMapping注解的value属性必须设置,至少通过请求地址匹配请求映射

webapp/WEB-INF/templates目录下的 index.html :

<a th:href="@{/testRequestMapping}">测试@RequestMapping的value属性-->/testRequestMapping</a><br>
<a th:href="@{/test}">测试@RequestMapping的value属性-->/test</a><br>

controller包下的RequestMappingController.java类:

@RequestMapping(
    value = {"/testRequestMapping", "/test"}
)
public String testRequestMapping(){
    return "success";
}

@RequestMapping注解的method属性

@RequestMapping注解的method属性通过请求的请求方式(get或post)匹配请求映射

@RequestMapping注解的method属性是一个RequestMethod类型的数组,表示该请求映射能够匹配多种请求方式的请求

若当前请求的请求地址满足请求映射的value属性,但是请求方式不满足method属性,则浏览器报错 405:Request method ‘POST’ not supported

method不设置 默认任何请求方式都能匹配(前提是请求路径能匹配上);所以requestmapping注解的属性其实是请求匹配的限制条件(约束条件),注解的属性越多,匹配条件越苛刻,匹配越精确。

webapp/WEB-INF/templates目录下的 index.html中:

<a th:href="@{/test}">测试@RequestMapping的value属性-->/test</a><br>
<form th:action="@{/test}" method="post">
    <input type="submit">
</form>

controller包下的RequestMappingController.java类:

@RequestMapping(
        value = {"/testRequestMapping", "/test"},
        method = {RequestMethod.GET, RequestMethod.POST}  //表示可以匹配POST请求 
)
public String testRequestMapping(){
    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,在RESTful部分会讲到

@RequestMapping注解的params属性(了解)

@RequestMapping注解的params属性通过请求的请求参数匹配请求映射

@RequestMapping注解的params属性是一个字符串类型的数组,可以通过四种表达式设置请求参数和请求映射的匹配关系

"param":要求请求映射所匹配的请求必须携带param请求参数

"!param":要求请求映射所匹配的请求必须不能携带param请求参数

"param=value":要求请求映射所匹配的请求必须携带param请求参数且 param=value

param!=value:要求请求映射所匹配的请求必须携带param请求参数但是 param!=value

webapp/WEB-INF/templates目录下的 index.html中:

<a th:href="@{/test(username='admin',password=123456)">测试@RequestMapping的params属性-->/test</a><br>

controller包下的RequestMappingController.java类:

@RequestMapping(
	value = {"/testRequestMapping","/test"}
   	,method = {RequestMethod.GET, RequestMethod.POST}
    ,params = {"username",password != 123456}  //表示传入的password不能是123456
)
public String testRequestMapping(){
    return "success";
}

注:

若当前请求满足@RequestMapping注解的value和method属性,但是不满足params属性,此时页面会报错400:Parameter conditions “username, password!=123456” not met for actual request parameters: username={admin}, password={123456}

@RequestMapping注解的headers属性(了解)

@RequestMapping注解的headers属性通过请求的请求头信息匹配请求映射

@RequestMapping注解的headers属性是一个字符串类型的数组,可以通过四种表达式设置请求头信息和请求映射的匹配关系

"header":要求请求映射所匹配的请求必须携带header请求头信息

"!header":要求请求映射所匹配的请求必须不能携带header请求头信息

"header=value":要求请求映射所匹配的请求必须携带header请求头信息且header=value

"header!=value":要求请求映射所匹配的请求必须携带header请求头信息且header!=value

若当前请求满足@RequestMapping注解的value和method属性,但是不满足headers属性,此时页面显示404错误,表示请求的资源未找到

  1. 如果没有跟任何一个request的method的value匹配,或者请求头不匹配,报404错误
  2. 如果请求方式匹配不了,报405错误(405表示指定的资源不支持请求的HTTP方法,如GET/POST/PUT/DELETE)
  3. 如果当前的请求方式不成功,报400错误

SpringMVC支持ant风格的路径

?:表示任意的单个字符 (这些符号不可以表示 ? / \ [ ] % ;)

*:表示任意的0个或多个字符

**:表示任意的一层或多层目录

注意:在使用**时,只能使用/**/xxx的方式,表示中间可以有任几层目录

controller包下的RequestMappingController.java类:

//    @RequestMapping("/a?a/testAnt")
//    @RequestMapping("/a*a/testAnt")
    @RequestMapping("/**/testAnt")
    public String testAnt(){
        return "success";
    }

webapp/WEB-INF/templates包下的 index.html中:

<!--http://localhost:8080/springMVC/a1a/testAnt-->
	<a th:href="@{/a1a/testAnt}">测试@RequestMapping可以匹配ant风格的路径--->使用?</a>   <br>

<!--http://localhost:8080/springMVC/abyxl8112a/testAnt -->
    <a th:href="@{/hello/abyxl8112a/testAnt}">测试@RequestMapping可以匹配ant风格的路径--->使用*</a>  <br>

<!--http://localhost:8080/springMVC/a/a/a/testAnt-->
    <a th:href="@{/hello/a/a/a/testAnt}">测试@RequestMapping可以匹配ant风格的路径--->使用**</a> <br>

SpringMVC支持路径中的占位符(重点)

原始方式:/deleteUser?id=1

rest方式:deleteUser/1

SpringMVC路径中的占位符常用语于 RESTful 风格中,当请求路径中将某些数据通过路径的方式传输到服务器中,就可以在相应的@RequestMapping注解的value属性中通过占位符{xxx}表示传输的数据,在通过 @PathVariable 注解,将占位符所表示的数据赋值给控制器方法的形参。@PathVariable注解用于从URL中获取请求参数的值,它可以将URL中的变量绑定到方法的参数上。

controller包下的RequestMappingController.java类:

//  SpringMVC支持路径中的占位符 rest方式
@RequestMapping("/testPath/{id}/{username}")
public String testPath(@PathVariable("id") Integer id, @PathVariable("username") String username){
    return "success";
}

webapp/WEB-INF/templates包下的 index.html中:

<!--直接传入值1,admin,表示id=1,username=admin-->
<a th:href="@{/testPath/1/admin}">测试@RequestMapping支持路径中的占位符-->/testPath </a>  <br>

SpringMVC中的REST占位符是一种用于处理URL路径参数的机制。REST(Representational State Transfer)是一种基于HTTP协议的网络应用程序架构风格,它强调资源的直接访问和状态转换的无状态性。在REST中,URL中的路径参数可以用于标识资源和资源状态,而REST占位符就是一种用于处理这些路径参数的机制。

在SpringMVC中,REST占位符可以通过在URL路径中使用“{}”符号来定义,例如“/users/{id}”。SpringMVC会将路径中的占位符提取出来,并将其作为方法的参数传递给控制器方法,从而实现URL路径参数的处理。例如,如果请求的URL为“/users/123”,那么SpringMVC会将“123”作为参数传递给控制器方法。

REST占位符可以用于处理各种类型的URL路径参数,例如数字、字符串、日期等。在处理URL路径参数时,SpringMVC还可以使用正则表达式和自定义类型转换器等技术,进一步增强REST占位符的灵活性和可扩展性。

总之,SpringMVC中的REST占位符是一种用于处理URL路径参数的机制,它可以通过在URL路径中使用“{}”符号来定义,并将路径参数作为方法的参数传递给控制器方法。REST占位符是实现基于HTTP协议的RESTful服务关键的一部分,它可以增强Web应用程序的可维护性和可扩展性。

dispatchServlet调用当前控制器方法是在dispatchServlet中执行的,通过请求地址和@RequestMapping这个注解来执行

在dispatchServlet中,封装了很多的数据,当调用控制器方法的时候,会根据控制器方法的参数来为当前的方法注入这个参数,也就是为参数赋值

实际上就是浏览器发送请求(包含参数的数据)被dispatchServlet接收,然后dispatchServlet解析地址,通过requestMapping注解找到对应方法,最后把获取的参数注入到方法中

代码:HttpServletRequest参数

@Controller
public class ParamController{
    
    @RequestMapping("/testServletAPI")
    public String testServletAPI(HttpServletRequest request){
        
    }
}

这个testServletAPI方法是dispatchServlet底层中来调用的,可以通过控制器方法的形参来为它注入不一样的值,比如说,如果它检测到这个方法的形参是HttpServletRequest对象,它就可以将在dispatchServlet里面所获得的表示当前请求的Request对象赋值给这个参数request。即:控制器方法中,如果写了request类型的参数,那么当前这个参数表示的就是当前的这个请求,即形参位置的request表示当前请求。之前我们在web.xml中注册前端控制器,浏览器发送的请求要先被前端控制器处理,dispatcherServlet会将请求地址赋值给这个参数reqeust

上面包括了浏览器发送过来的Request,此时dispatcherServlet就会自动把浏览器发送过来的Request赋值给控制器方法的形参request了。

SpringMVC获取请求参数

通过ServletAPI获取

将HttpServletRequest作为控制器方法的形参,此时HttpServletRequest类型的参数表示封装了当前请求的请求报文的对象

controller包下的ParamController.java类中

//形参位置的request表示当前请求
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request){
    HttpSession session = request.getSession();
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    System.out.println("username: " + username + "password: " + password);
    return "success";
}

通过控制器方法的形参获取请求参数

在控制器方法的形参位置,设置和请求参数同名的形参,当浏览器发送请求,匹配到请求映射时,在DispatchServlet中就会将请求参数赋值给相应的形参,形参的参数名要和请求参数的参数名保持一致才能够正常获取

webapp/WEB-INF/templates包下的 test_param.html中:

<!--    http://localhost:8080/springMVC/testParam?username=admin&password=1234567 -->
    <a th:href="@{/testParam(username='admin',password=1234567)}">测试使用控制器的形参获取请求参数</a><br>

controller包下的ParamController.java类中

@RequestMapping("/testParam")
public String testParam(String username, String password){
    System.out.println("username:" + username + ",password:" + password);
    return "success";
}

注:

若请求所传输的请求参数中有多个同名的请求参数,此时可以在控制器方法的形参中设置字符串数组或者字符串类型的形参接收此请求参数

若使用字符串数组类型的形参,此参数的数组中包含了每一个数据

若使用字符串类型的形参,此参数的值为每个数据中间使用逗号拼接的结果

数组例子:

controller包下的ParamController.java类中:

@RequestMapping("/testParam")
    public String testParam(String username,
                            String password,
                            String[] hobby){
        System.out.println("username: " + username + " password: " + password + " hobby: " + Arrays.toString(hobby));
        return "success";
    }

webapp/WEB-INF/templates包下的 test_param.html中:

<form th:action="@{/testParam}" method="get">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    爱好:<input type="checkbox" name="hobby" value="a">a
    <input type="checkbox" name="hobby" value="b">b
    <input type="checkbox" name="hobby" value="c">c<br>
    <input type="submit" value="测试使用控制器的形参获取请求参数">
</form>
image-20230601135940840

测试结果:

image-20230601140042395

image-20230601141222155

@RequestParam

@RequestParam 是将请求参数和控制器方法的形参创建映射关系

@RequestParam 注解一共有三个属性:

  • value:指定为形参赋值的请求参数的参数名
  • required:设置是否必须传输value的请求参数,默认值为true(必须传输),如果设置为false的话,有则传输,没有则默认值
    • 若设置为true,在当前请求必须传输 value 所指定的请求参数,若没有传输该请求参数,且没有设置 defaultValue 属性,则页面报错 400:Required String parameter ‘xxx’ is not present;
    • 若设置为false,则当前请求不是必须传输 value 所指定的请求参数,若没有传输,则注解所标识的形参的值为 null
  • defaultValue:不管 required 属性值为true或false,当value所指定的请求参数没有传输或传输的值为 “” (空字符串)时,则使用默认值为形参赋值。

测试1:required=true,且没有设置defaltValue

必须要传value值,不传则报错

controller 包下的 ParamController.java类下:

@RequestMapping("/testParam")
public String testParam(@RequestParam(value="username", required=true)String username,
                        String password,
                        String[] hobby){
    System.out.println("username: " + username + " password: " + password + " hobby: " + Arrays.toString(hobby));
    return "success";
}

webapp/WEB-INF/templates包下的 test_param.html中:

<form th:action="@{/testParam}" method="get">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    爱好:<input type="checkbox" name="hobby" value="a">a
    <input type="checkbox" name="hobby" value="b">b
    <input type="checkbox" name="hobby" value="c">c<br>
    <input type="submit" value="测试使用控制器的形参获取请求参数">
</form>
image-20230601142048375

会报错:

image-20230601142225310

测试2:required=true,且defaultValue=”byxl8112”

必须要传,不传username则使用默认值 byxl8112

controller 包下的 ParamController.java类下:

@RequestMapping("/testParam")
public String testParam(@RequestParam(value="username", required=true, defaultValue="byxl8112")String username,
                        String password,
                        String[] hobby){
    System.out.println("username: " + username + " password: " + password + " hobby: " + Arrays.toString(hobby));
    return "success";
}

webapp/WEB-INF/templates包下的 test_param.html中:

<form th:action="@{/testParam}" method="get">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    爱好:<input type="checkbox" name="hobby" value="a">a
    <input type="checkbox" name="hobby" value="b">b
    <input type="checkbox" name="hobby" value="c">c<br>
    <input type="submit" value="测试使用控制器的形参获取请求参数">
</form>
image-20230601142048375

测试结果:使用了username默认值 byxl8112

image-20230601142937226

测试3:required=false,且没有设置defaultValue

不必须要传,没有设置defaultValue的话,则其值为null

controller 包下的 ParamController.java类下:

@RequestMapping("/testParam")
public String testParam(@RequestParam(value="username", required=false)String username,
                        String password,
                        String[] hobby){
    System.out.println("username: " + username + " password: " + password + " hobby: " + Arrays.toString(hobby));
    return "success";
}

webapp/WEB-INF/templates包下的 test_param.html中:

<form th:action="@{/testParam}" method="get">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    爱好:<input type="checkbox" name="hobby" value="a">a
    <input type="checkbox" name="hobby" value="b">b
    <input type="checkbox" name="hobby" value="c">c<br>
    <input type="submit" value="测试使用控制器的形参获取请求参数">
</form>
image-20230601142048375

测试结果:required=false,且没有设置defaultValue,username的值为null;

image-20230601143514354

测试4:required=false,且defaultValue=byxl8112

不必须要传,不传则使用默认值defaultValue=byxl8112

controller 包下的 ParamController.java类下:

@RequestMapping("/testParam")
public String testParam(@RequestParam(value="username", required=false, defaultValue="byxl8112")String username,
                        String password,
                        String[] hobby){
    System.out.println("username: " + username + " password: " + password + " hobby: " + Arrays.toString(hobby));
    return "success";
}

webapp/WEB-INF/templates包下的 test_param.html中:

<form th:action="@{/testParam}" method="get">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    爱好:<input type="checkbox" name="hobby" value="a">a
    <input type="checkbox" name="hobby" value="b">b
    <input type="checkbox" name="hobby" value="c">c<br>
    <input type="submit" value="测试使用控制器的形参获取请求参数">
</form>
image-20230601142048375

测试结果:没有传username,则使用了defaultValue=byxl8112

image-20230601144005433

@RequestHeader

@RequestHeader是将请求头信息和控制器方法的形参创建映射关系

@RequestHeader注解一共有3个属性:value、required、defaultValue,用法同@RequestParam一样

@CookieValue

@CookieValue是将cookie数据和控制器方法的形参创建映射关系

@CookieValue注解一共有三个属性:value、required、defaultValue,用法同@RequestParam一样

回顾拓展cookie:

Session依赖于Cookie,Session是服务器的会话技术,Cookie是客户端的会话技术。

Cookie是一小段存储在浏览器的文本数据,它是session或token的载体,也就是说cookie保存了session或token

session保存在服务器的池中,需要用key来标识这个session,这个key以cookie的形式保存在浏览器端,JsessionID每当浏览器访问的时候,用getSession实际上通过这个id去匹配服务器session池中的session,如果有就拿过来,没有就新建

javaWeb阶段,你会发现如果把那个cookie删除,session每次搞得都是新的,因为没办法获取到之前的key没了,这样服务器那边就会有很多没用的session

JSESSIONID是Java EE Web应用程序中用于实现会话跟踪的一种机制。当用户第一次访问一个Web应用程序时,Web服务器会创建一个唯一的会话ID,并将它存储在一个名为JSESSIONID的Cookie中。当用户浏览其他页面时,Web浏览器会自动将JSESSIONID发送回Web服务器,以便Web服务器可以使用会话ID来跟踪用户的会话状态,cookie创建之后会存在于请求报文中

通过 POJO 获取请求参数

可以在控制器方法的形参位置设置一个实体类类型的形参,此时,若浏览流程传输的请求参数的参数名和实体类中的属性名一致,那么请求参数就会为此属性赋值。

pojo包(或bean)下的User.java类:

public class User{
    private String username;
    private String password;
    private Integer age;
    private String sex;
    private String email;
    
    ...  //空参构造器、username,password,age,sex,email构造器、get/set方法、toString方法
}

webapp/WEB-INF-templates包下的test_param.html中:

<form th:action="@{/testBean}" method="post">
    用户名:<input type="text" name="username"> <br>
    密码:<input type="password" name="password"> <br>
    性别:<input type="text" name="gender"> <br>
    年龄:<input type="text" name="age"> <br>
    邮箱:<input type="text" name="email"> <br>
    <input type="submit" value="使用实体类接收请求参数">
</form>

controller包下的ParamController.java类:

@RequestMapping("/testBean")
public String testBean(User user){
    System.out.println(user);
    System.out.println(user.getAge());
    return "success";
}
image-20230622122715608

解决获取请求参数的乱码问题

在处理HTTP请求时,如果请求参数包含非ASCII字符集的内容,例如中文、日文、韩文等,可能会出现乱码问题。这是因为HTTP请求默认使用ISO-8859-1字符集进行编码,而非ASCII字符集的内容需要使用其他字符集进行编码。

为了解决这个问题,我们可以在Web服务器和Web应用程序之间进行字符集转换。具体来说,当Web服务器接收到HTTP请求时,它应该将请求参数的编码格式从ISO-8859-1转换为正确的字符集。当Web应用程序接收到HTTP请求时,它应该将请求参数的字符集从正确的字符集转换为Java内部使用的Unicode字符集。

在Java Web应用程序中,我们可以通过在web.xml文件中添加一个过滤器来实现字符集转换。以下是一个示例:

<!--配置springMVC的编码过滤器-->
<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>

因为请求和响应都是一个参数encoding,我们配置一次即可,只配置encoding的话只设置请求的格式。如果请求和响应都想设置,需要设置encoding和forceResponseEncoding

注意:SpringMVC中处理编码的过滤器一定要配置到其他过滤器之前,否则无效

域对象共享数据

三种域对象:

  1. request:一次请求

    使用request情况列举:列表功能、修改回显功能、错误信息提示

  2. session:一次会话 -> 浏览器开启到浏览器关闭的过程

    • session中的数据和服务器是否关闭没有关系,只跟浏览器是否关闭有关系,因为session中有钝化和活化

      • 钝化:当服务器关闭了,但是浏览器没有关闭,说明这个会话仍然在继续,这个时候存储在session中的数据会经过序列化,序列化到子盘上
      • 活化:如果浏览器没有关闭,但是服务器重新开启了,服务器会找到之前钝化之后的文件内容重新读取到session中,从中恢复之前保存起来的Session 对象,这个过程叫做Session的活化。

      如果服务器关闭,会在本地文件生成一个可序列化的session文件,服务器重启后,这个文件重新写入到服务器,然后删除本地的session文件。

    session使用情况举例:保存用户的登录状态

  3. servletContext(application):整个应用的范围(服务器开启到服务器关闭),表示的是上下文对象,只在服务器开启的时候创建,在服务器关闭时销毁,与浏览器是否关闭没有关系,只跟服务器是否关闭有关系

使用ServletAPI向request域对象共享数据

  • setAttribute:向域对象中共享数据
    • 第一个参数:当前共享数据的键(String类型)
    • 第二个参数:当前共享数据的值(Object类型)
  • getAttribute:向域对象中获取数据
  • removeAttribute:向域对象删除共享数据

controller包下的ScopeCotroller.java类:

//使用servletAPI向request域中共享数据
@RequestMapping("/testRequestByServletAPI")
public String testRequestByServletAPI(HttpServletRequest request){
    //向域对象中共享数据
    request.setAttribute("testRequestScope", "hello, servletAPI");
    return "success";
}

webapp/WEB-INF/templates包下的index.html:

<a th:href="@{/testRequestByServletAPI}">通过servletAPI(HttpRequest)向request域对象共享数据</a>

webapp/WEB-INF/templates包下的success.html:

<h1>success</h1>
<!--输出request域中testRequestScope键的值-->
<p text="testRequestScope"></p>

输出结果:

image-20230622125059877

使用ModelAndView向request域对象共享数据(重要)

model:封装模型数据,指的是往域对象中共享数据的功能

view:封装视图信息,指的是最终所设置的视图名称经过视图解析器解析跳转到指定的页面的过程

cotroller包下的ScopeController类:

@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
    //new ModelAndView对象
    ModelAndView mav = new ModelAndView();
    //处理模型数据,向请求域共享数据
    mav.addObject("testRequestScope", "hello, ModelAndView");
    //设置视图名称,实现页面跳转
    mav.setViewName("success");
    return mav;
}

webapp/WEB-INF/templates包下的index.html:

<a th:href="@{/testModelAndView}">通过ModelAndView向request域对象共享数据</a>

webapp/WEB-INF/templates包下的success.html:

<h1>success</h1>
<!--输出request域中testRequestScope键的值-->
<p text="testRequestScope"></p>

输出结果:

image-20230622125059877

使用Model向request域对象共享数据

ModelAndView不写形参是因为它是被返回的,但现在model返回的是String,所以model必须是框架给的,不能是自己创建的

  • 使用ModelAndView时,必须要是ModelAndView作为方法的返回值返回。
  • 直接使用Model时,可以在形参的地方设置Model形参,但在设置视图的方式还是跟原来的方式一样的。

Model是一个接口

controller包下的ScopeController.java类:

@RequestMapping("/testModel")
public String testModel(Model model){
    //处理模型数据,向请求域共享数据
    model.addAttribute("testRequestScope","hello, Model");
    //通过反射获取输出类型  org.springframework.validation.support.BindingAwareModelMap
    System.out.println(model.getClass().getName()); 
    return "success";
}

webapp/WEB-INF/templates包下的index.html:

<a th:href="@{/testModel}">通过Model向request域对象共享数据</a>

webapp/WEB-INF/templates包下的success.html:

<h1>success</h1>
<p text="testRequestScope"></p>

输出结果:

image-20230622125059877

使用Map向request域对象共享数据

在形参中创建一个Map集合,我们往Map集合中存放的数据就是往域对象中共享的数据,Map集合中键和值的类型要和往域对象中所存储的键和值的类型要保持一致。

controller包下的ScopeController.java类:

@RequestMapping("/testMap")
public String testMap(Map<String,Object> map){
    map.put("testRequestScope", "hello, Map");
    return "success";
}

webapp/WEB-INF/templates包下的index.html:

<a th:href="@{/testMap}">通过Map向request域对象共享数据</a>

webapp/WEB-INF/templates包下的success.html:

<h1>success</h1>
<p th:text="${testRequestScope}"></p>

输出结果:

image-20230622125059877

使用ModelMap向request域对象共享数据

ModelMap继承了LinkedHashMap类,也就是说实现了Map接口

controller包下的ScopeController.java类:

@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelmap){
    modelmap.addAttribute("testRequestScope", "hello, ModelMap");
    return "success";
}

webapp/WEB-INF/templates包下的index.html:

<a th:href="@{/testModelMap}">通过ModelMap向request域对象共享数据</a>

webapp/WEB-INF/templates包下的success.html:

<h1>success</h1>
<p th:text="${testRequestScope}"></p>
image-20230622125059877

Model、ModelMap、Map的关系

Model、ModelMap、Map类型的参数其实本质上都是 BindingAwareModelMap 类型的

public interface Model{}
public class ModelMap extends LinkedHashMap<String, Object> {}
public class ExtendedModelMap extends ModelMap implements Model {}
public class BindingAwareModelMap extends ExtendedModelMap {}

BindingArareModelMap 可以实例化ModelMap ,也可以实例化Model,因为ModelMap继承了Map,所以BindingArareModelMap也可以实例化Map

在SpringMVC中,从浏览器发送到服务器的请求,都要被DispatcherServlet前端控制器进行处理,当我们去调用了控制器方法,我们最终获得的就是ModelAndView对象。控制器方法执行完之后,在DispatcherServlet,最终都要将模型和视图信息封装成一个ModelAndView

在Spring MVC中,Model、ModelMap和Map都是用于在Controller方法中传递数据到View的数据结构。它们之间的关系如下:

  1. Model是Spring MVC框架中定义的一个接口,用于封装Controller方法中需要传递给View的数据。它提供了一些方法来添加、获取和删除数据。当Controller方法返回View名称时,Spring MVC框架会将Model中的数据自动传递给View。

  2. ModelMap是Model接口的实现类,它可以看作是一个拥有更多方法的Model接口。除了Model接口的方法外,它还提供了一些额外的方法来方便地添加、获取和删除数据。例如,ModelMap的addAttribute()方法可以使用一个键值对来添加数据。

  3. Map是Java集合框架中的一个接口,它定义了一些用于存储键值对的方法。在Spring MVC中,Controller方法可以使用Map作为参数来传递数据到View。当Controller方法返回View名称时,Spring MVC框架会将Map中的数据自动传递给View。

因此,从功能和用法上来说,Model、ModelMap和Map都可以用于在Controller方法中传递数据到View。但是,由于Model和ModelMap是专门为Spring MVC框架设计的接口和实现类,它们提供了更多的方法和功能,因此通常比Map更加方便和易用。同时,使用Model和ModelMap还可以让代码更加清晰和易于理解。

向session域共享数据

建议使用原生API(HttpSession)向session域共享数据

controller包下的ScopeController.java类:

@RequestMapping("/testSession")
public String testSession(HttpSession session){
    session.setAttribute("testSessionScope", "hello, session");
    return "success";
}

webapp/WEB-INF/templates包下的index.html:

<a th:href="/testSession">通过servletAPI(HttpSession)向session域对象共享数据</a>

webapp/WEB-INF/templates包下的success.html:

<h1>success</h1>
<!--如果访问的是session域中的数据,需要写 session.共享数据的键-->
<p th:text="${session.testSessionScope}"></p>
image-20230622195243062

向application域共享数据

application也是一个域对象,它对应的范围是当前整个工程的范围:

因为当前的servletContext对象是在服务器启动时创建的,而在当前服务器整个工作的过程中创建的ServletContext对象都是同一个

application指的就是ServletContext,所以只需要获取ServletContext对象即可

获取ServletContext对象的方式:

  1. 在javax.servlet.Filter中直接获取:

    servletContext contex = filterConfig.getServletContext();

  2. 在Httpservlet中直接获取

    this.getServletContext()

  3. 在其他方法中,通过ServletRequest、HttpServletRequest获取

    request.getServletContext();

    同样:session也可以获取 -> session.getServletContext();request.getSession().getServletContext();

  4. 在Servlet中init方法(Servlet初始化方法),这里有个ServletConfig对象,表示当前Servlet的一个配置信息,它可以来获取当前servlet的友好名称,就是在注册的时候servlet-name这个标签的值,它还可以来获取当前servlet的初始化参数,它还可以来获取servletContext对象

controller包下的ScopeController.java类:

@RequestMapping("/testApplication")
public String testApplication(HttpSession session){
    ServletContext application = session.getServletContext();
    application.setAttribute("testApplicationScope", "hello, Application");
    return "success";
}

webapp/WEB-INF/templates包下的index.html:

<a th:href="@{/testApplication}">通过servletAPI(HttpSession)向application域对象共享数据</a>

webapp/WEB-INF/templates包下的success.html:

<h1>success</h1>
<!--如果访问的是application域(ServletContext域) 中的值,需要写 application.共享数据的键-->
<p th:text="${application.testApplicationScope}"></p>

输出结果:

image-20230623101627475

SpringMVC的视图

SpringMVC中的视图是View接口,视图的作用渲染数据,将模型Model中的数据展示给用户

SpringMVC视图的种类很多,默认有转发视图InternalResourceView和重定向视图RedirectView

当工程引入jstl的依赖,转发视图会自动转换为JstlView

若使用的视图技术为Thymeleaf,在SpringMVC的配置文件中配置了Thymeleaf的视图解析器,由此视图解析器解析之后所得到的是ThymeleafView

ThymeleafView

当控制器方法中所设置的视图名称没有任何前缀时,此时的视图名称会被SpringMVC配置文件中所配置的视图解析器(ThymeleafViewResolver)解析,被它解析的视图就是ThymeleafView,视图名称拼接视图前缀和视图后缀所得到的最终路径,会通过转发的方式实现跳转,用了ThymeleafView之后,这个html页面必须要通过转发进行访问(跳转到某一个html的请求),因为Html页面中有th标签,必须由Thymeleaf在服务器端解析后才能获取结果使用,所以必须要转发。

html本来是静态页面,通过thymeleaf渲染实际上就是数据的动态变化,静态到动态的改变。以前的html可没办法从服务器端获取数据并且显示,咱们用的EL和JSTL输出数据都是基于jsp页面进行的

视图解析器说明:配置视图解析器可以用ThymeleafResolver也可以用InternalResolver,区别就是用后者,你不写forward也相当于写了。前面说jsp页面默认是Internal Resource的意思就是配置的视图解析器是这个解析器,什么解析器默认就是什么不需要加前缀了。

@RequestMapping("/testHello")
public String testHello(){
    return "hello";
}
image-20230623104136487

创建的视图对象只跟视图名称有关系,如果没有前缀,那么创建的就是ThymeleafView,如果有前缀,若是 redirect:,创建的就是重定向视图,若是forword: ,创建的就是转发视图

上面是源码:通过视图名称来获取视图对象。

  • viewName:String viewName = mv.getViewName();:从ModelAndView中获取视图名称
  • mv.getModelInternal ( ):model所封装的模型数据

当要通过转发或重定向的时候,这时候不能添加前缀和后缀,那么这时候就需要使用forward:redirect:,也能看出来其实thymeleaf适合页面的跳转,但是对于需要获取数据并且显示的页面,显然不适合用thymeleaf,因为如果用thymeleaf解析,会进行前后缀拼接,肯定不满足条件,因为现在需要的是跳转到Servlet或者说进行一次请求

Thymeleaf不是转发或重定向的机制,而是用于生成响应的模板引擎。通常情况下,我们可以将Controller方法返回一个逻辑视图名,然后让Spring MVC框架将逻辑视图名解析成具体的Thymeleaf模板,最终生成响应。如果需要进行转发或重定向,我们可以在Controller方法中使用Spring MVC提供的转发或重定向机制。

转发和重定向的区别:

  • 转发:一次请求,第一次浏览器发送,(第二次是发生在服务器内部进行跳转(所以最终地址栏还是第一次发送请求的地址));重定向:两次请求,第一次访问servlet,第二次访问重定向到的地址;最终的地址是第二次重定向到的地址
  • 转发可以获取请求域中的数据,重定向不能获取请求域中的数据,因为转发是一次请求,一次请求说明用到的request对象是同一个,而重定向浏览器发送了两次请求,两次请求就对应了两个request对象
  • 转发能访问WEB-INF下的资源,但重定向不能访问WEB-INF下的资源,因为WEB-INF下的资源具有安全性/隐藏性,只能通过服务器内部来访问,不能通过浏览器来访问
  • 转发不能跨域,重定向可以跨域。跨域:转发是发生在服务器内部的,那它就只能访问服务器内部的资源;而浏览器发送的两次请求,那可以通过浏览器可以访问任何资源,比如说,在当前的工程里面,可以重定向到百度

转发视图

首先要明确请求转发视图功能底层使用的是缓冲池技术(其目的就是复用,提高运行效率,经常用的请求就放在里面),

SpringMVC中创建转发视图的情况:

当控制器方法中所设置的视图名称没有前缀或者以”forward:”开头的时候,创建InternalResourceView视图,此时的视图名称不会被SpringMVC配置文件中所配置的视图解析器解析,而是会将前缀”forward:”去掉,剩余部分作为最终路径通过转发的方式实现跳转

例如”forward:/“ (转发到首页),”forward:/employee(转发到/employee这个地址)”

//创建ThymeleafView
@RequestMapping("/testThymeleafView")
public String testThymeleafView(){
    return "success";
}
//最终路径是:http://localhost:8080/springMVC/testThymeleafView
//创建testForward
@RequestMapping("/testForward")
public String testForward(){
    return "forward:testThymeleafView";  //转发到testThymeleafView这个地址
}
//最终路径是:http://localhost:8080/springMVC/testForward

SpringMVC中默认的转发视图是 InternalResourceView,将前缀(forward:)去掉,剩余部分要通过转发来进行访问,这个过程就会来创建转发视图InternalResourceView,当找到testThymeleafView这个请求映射的时候,需要在创建一次view,这次创建的view是ThymeleafView

image-20230623111052773

重定向视图

SpringMVC中默认的重定向视图是RedirectView

当控制器方法中所设置的视图名称以redirect:为前缀时,创建RedirectView视图,此时的视图名称不会被SpringMVC配置文件中所配置的视图解析器解析,而是会将前缀redirect:去掉,剩余部分作为路径通过重定向的方式实现跳转

发送第一次请求的过程会创建Thymeleaf请求,第二次也是Thymeleaf请求

例如:”redirect:/“(重定向到首页),”redirect:/employee” (重定向到/employee这个地址)

//创建ThymeleafView
@RequestMapping("/testThymeleafView")
public Stirng testThymeleafView(){
    return "success";
}
//最终路径是:http://localhost:8080/springMVC/testThymeleafView
//创建testRedirect重定向
@RequestMapping("/testRedirect")
public String testRedirect(){
    return "redirect:testThymeleafView";  //重定向到testThymeleafView
}
//最终路径是:http://localhost:8080/springMVC/testThymeleafView

image-20230623113129287

注:重定向视图在解析时,会先将redirect:前缀去掉,然后会判断剩余部分是否以/开头,若是则会自动拼接上下文路径

视图控制器view-controller

视图控制器 view-controller就是springMVC中的一个标签,它也是来帮助我们当前的请求地址和视图之间的一个映射关系

当控制器方法中,仅仅用来实现页面跳转,即只需要设置视图名称时,可以将处理器方法使用 view-controller 标签进行表示在我们当前的请求映射所对应的控制器方法中没有其他请求过程的处理,只需要来设置一个视图名称的时候,可以使用view-cntroller

spring配置文件springMVC.xml

<!--
	path:设置处理的请求地址,跟RequestMapping中的value一样
	view-name:设置请求地址所对应的视图名称
-->
<!--表示跳转到首页index.html-->
<mvc:view-controller path="/" view-name="index"></mvc:view-controller>

注:当SpringMVC中设置任何一个view-controller时,其控制器中的请求映射将全部失效,此时需要在SpringMVC的核心配置文件中(springMVC.xml)设置开启mvc注解驱动的标签:<mvc:annotation-driven />

RESTful

RESTful简介

就是来做一个统一,有一个统一的规则,对于当前操作的这个业务统一,这个业务功能的命名不用操心,同一个url根据请求方式不同区分是增删改查的哪一种请求。

相当于要对一个资源进行操作,不管用什么方式,只是方式变了,但是最终都是输入这个请求路径,只不过这个路径操作方式不一样可能是get是post是put是delete,但是这4种方式操作的路径是同一个

RESIful 是一个软件架构的格式。REST:Representational State Transfer,表现层资源状态转移

a>资源

资源是一种看待服务器的方式,即,将服务器看作是由很多离散的资源组成。每个资源是服务器上一个可命名的抽象概念。因为资源是一个抽象的概念,所以它不仅仅能代表服务器文件系统中的一个文件、数据库中的一张表等等具体的东西,可以将资源设计的要多抽象有多抽象,只要想象力允许而且客户端应用开发者能够理解。与面向对象设计类似,资源是以名词为核心来组织的,首先关注的是名词。一个资源可以由一个或多个URI来标识。URI既是资源的名称,也是资源在Web上的地址。对某个资源感兴趣的客户端应用,可以通过资源的URI与其进行交互。

b>资源的表述(资源的状态)

资源的表述是一段对于资源在某个特定时刻的状态的描述。可以在客户端-服务器端之间转移(交换)。资源的表述可以有多种格式,例如HTML/XML/JSON/纯文本/图片/视频/音频等等。资源的表述格式可以通过协商机制来确定。请求-响应方向的表述通常使用不同的格式。

c>状态转移

状态转移说的是:在客户端和服务器端之间转移(transfer,就是浏览器发送请求到服务器,服务器需要响应,将服务器长的资源转移到当前的客户端)代表资源状态的表述(请求路径)。通过转移和操作资源的表述,来间接实现操作资源的目的。

比如登入时客户端发送帐号、密码的文本信息,服务端匹配成功后返回登录成功页面,资源指服务器上的网页、图片、文本等等文件,统称网页资源,状态转移就是网页资源在客户端和服务器交换的过程

RESTful的实现

RESTful:相同的请求方式,不同的请求路径,来表示不同的操作

具体说,就是 HTTP 协议里面,四个表示操作方式的动词: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请求方式

使用RESTFul模拟用户资源(user)的增删改查

路径 请求方式 功能

/user GET 查询所有用户信息

/user/1 GET 根据用户id查询用户id=1的用户信息

/user POST 添加用户信息

/user/1 DELETE 删除用户id=1的用户信息

/user PUT 修改用户信息

controller包下的UserController.java类

//使用RESTful模拟用户资源的增删改查

@Controller
public class UserController(){
    
    //查找所有用户
    @RequestMapping(value="/user", method=RequestMethod.GET)
    public String getAllUser(){
        System.out.println("查询所有用户信息");
        return "success";
    }
    
    //根据用户id进行查找
    @RequestMapping(value="/user{id}", method=RequestMethod.GET)
    public String getUserById(){
        System.out.println("用户的id是: " + id);
        return "success";
    }
    
    //根据用户的id删除用户
    @RequestMapping(value="/user{id}", method=RequestMethod.DELETE)
    public String deleteUserById(@PathVariable Integer id){
        System.out.println("删除用户的id是: " + id);
        return "success";
    }
    
    //修改用户信息
    @RequestMapping(value="/user", method=RequestMethod.PUT)
    public String modifyUser(User user){
        Sytem.out.println(user.toString());
        return "success";
    }
    
    //添加用户
    @RequestMapping("/user", method=RequestMethod.POST)
    public String saveUser(){
        System.out.println("添加用户信息");
        return "success";
    }
}

一个请求可能包含以下URL:/users/123

@PathVariable注解绑定到方法的id参数上,这样Spring MVC框架就会自动从URL中提取出id变量的值,并将其赋值给方法中的id参数。这样,我们就可以使用该参数来查询对应的用户信息了。

@PathVariable注解默认是必须匹配URL中对应的变量的,如果URL中没有对应的变量,则会抛出异常。如果想要让变量是可选的,可以使用required属性将其设置为false

以上程序代码也可以用多个结合注解来表示:

//@Controller
//@ResponseBody
@RestController
@RequestMapping("/users")
public class UserController {

//    @RequestMapping(method = RequestMethod.POST)
    @PostMapping
//    @ResponseBody
    public String saveUser(){
        System.out.println("save the user");
        return "success_user";
    }

//    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @DeleteMapping("/{id}")
//    @ResponseBody
    public String deleteById(@PathVariable Integer id){
        System.out.println("delete the user by id = " + id);
        return "success_delete";
    }

//    @RequestMapping(method = RequestMethod.PUT)
    @PutMapping
//    @ResponseBody
    public String modifyUser(User user){
        System.out.println(user.toString());
        return "success_modify";
    }

//    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @GetMapping("/{id}")
//    @ResponseBody
    public String getById(@PathVariable Integer id){
        System.out.println("select the user by id = " + id);
        return "success_getById";
    }

//    @RequestMapping(method = RequestMethod.GET)
    @GetMapping
//    @ResponseBody
    public String getAll(){
        System.out.println("select the user");
        return "success_getAll";
    }
}
  • @RequestBody注解就是用来将请求体中的数据(例如JSON格式的数据)转换成对应的Java对象的。

  • @RestController 注解是 @Controller 注解和 @ResponseBody 注解的合体,拥有这两个注解的功能。

  • 在类上面的 @RequestMapping ( “/users” ) 注解表示这个类所有方法的匹配路径最前面的路径都是 “/users”

  • GETMappingPOSTMappingPUTMappingDELETEMapping 表示 method 值,里面可以传参数,此参数可以是 “/users” 之后的URL

HiddenHttpMethodFilter

由于浏览器只支持发送get和post方式的请求,那么该如何发送put和delete请求呢?

SpringMVC 提供了 HiddenHttpMethodFilter 帮助我们将 POST 请求转换为 DELETE 或 PUT 请求

HiddenHttpMethodFilter 处理put和delete请求的条件:

a>当前请求的请求方式必须为post

b>当前请求必须传输请求参数_method

html页面中:

<form th:action="@{/user}" method="post">
    <!--设置隐藏域hidden-->
    <input type="hidden" name="_method" value="put">  <br>
    用户名: <input type="text" name="username">  <br>
    密码: <input type="text" name="password">  <br>
    <input type="submit" value="修改">  <br>
</form>

满足以上条件,HiddenHttpMethodFilter 过滤器就会将当前请求方式转换为请求参数 _method 的值,因此请求参数 _method 的值才是最终的请求方式。

在 web.xml 中注册 HiddenHttpMethodFilter

<filter>
	<filter-name>HiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframwork.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
	<filter-name>HiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

注意:

目前为止,SpringMVC中提供了两个过滤器:CharacterEncodingFilter 和 HiddenHttpMethodFilter

在web.xml中注册时,必须先注册 CharacterEncodingFilter,再注册 HiddenHttpMethodFilter

原因:

  • 在 CharacterEncodingFilter 中通过 request.setCharacterEncoding(encoding) 方法设置字符集,这句话在此之前不能获取任何的请求参数,一旦获取了,那当前设置的编码方式就没有效果了

  • request.setCharacterEncoding(encoding) 方法设置编码要求前面不能有任何获取请求参数的操作

  • 而 HiddenHttpMethodFilter 恰恰有一个获取请求方式的操作:

  • ```
    String paramValue = request.getParameter(this.methodParam);

    
    如果要执行delete功能的话,通过vue在超链接上绑定一个点击事件,在点击事件里面先阻止超链接的默认行为(跳转),然后在获取当前的某一个表单,这个表单里面不需要有任何数据,只需要在这个form表单中将请求方式设置为post,里面写个隐藏域,name="_method",value="delete",也不需要写提交按钮,因为当前我们要做的就是超链接去控制表单的提交
    
    # RESTful案例
    
    ## 准备工作
    
    和传统CRUD一样,实现对员工信息的增删改查
    
    * 搭建环境
    * 准备实体类
    
    bean包下的 Employee.java类
    
    ```java
    public class Employee {
    
      private Integer id;
      private String lastName;
    
      private String email;
      //1 male, 0 female
      private Integer gender;
      
      public Integer getId() {
         return id;
      }
    
      public void setId(Integer id) {
         this.id = id;
      }
    
      public String getLastName() {
         return lastName;
      }
    
      public void setLastName(String lastName) {
         this.lastName = lastName;
      }
    
      public String getEmail() {
         return email;
      }
    
      public void setEmail(String email) {
         this.email = email;
      }
    
      public Integer getGender() {
         return gender;
      }
    
      public void setGender(Integer gender) {
         this.gender = gender;
      }
    
      public Employee(Integer id, String lastName, String email, Integer gender) {
         super();
         this.id = id;
         this.lastName = lastName;
         this.email = email;
         this.gender = gender;
      }
    
      public Employee() {
      }
    }

dao包下的EmployeeDao.java:

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.atguigu.mvc.bean.Employee;
import org.springframework.stereotype.Repository;


@Repository
public class EmployeeDao{
    
    private static Map<Integer, Employee> employees = null;
    
    static{
        employees = new HashMap<Integer, Employee>();
        
        employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1));
        employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1));
        employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0));
        employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0));
        employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1));
    }
    
    private static Integer initId = 1006;
    
    //添加
    public void save(Employee employee){
        if(employee.getId() == null){
            employee.setId(initId++);
        }
        employees.put(employee.getId(), employee);
    }
    
    //查找全部
    public Collection<Employee> getAll(){
        return employees.values();
    }
    
    //根据id查找
    public Employee get(Integer id){
        return employees.get(id);
    }
    
    //删除
    public void delete(Integer id){
        employees.remove(id);
    }
   
    
}

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.byxl8112.rest"/>

    <!--配置Thymeleaf视图解析器-->
    <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:view-controller path="/" view-name="index"/>
    <!--添加功能的视图解析器-->
    <mvc:view-controller path="/toAdd" view-name="employee_add"/>

    <!--开放对静态资源的访问-->
    <!--静态资源在被访问的时候会先被springMVC(前端控制器)来进行处理,
        如果在控制器中找不到请求映射,就会交给默认的servlet进行处理,如果默认的servlet能够找到相对应的资源,那就访问资源
        如果找不到相对应的资源,还是404
        DispatcherServlet会把对静态资源的访问当成一个请求,然后去找对应的RequestMapping,而静态资源没有对应的Controller就会报错说找不到
        如果浏览器当前发送的请求,DispatcherServlet处理不了,就会交给default来处理
        spring MVC处理不了交给默认的Servlet处理,有错的话控制台不会是spring MVC报错!
        如果不加default-servlet-handler,则都是DispatcherServlet来处理的,如果只加它,则都是default-servlet来处理的
    -->
    <mvc:default-servlet-handler/>

    <!--
    开启mvc注解驱动,要和default-servlet-handler一起来进行处理,
    如果不配置annotation-driven,所有请求都会被默认的DispatcherServlet来处理,当前只有静态资源能访问,其他的请求映射访问不了
    如果开启mvc注解驱动(annotation-driven)和静态资源访问(default-servlet),就是先被DispatcherServlet处理,
        如果它在匹配请求的时候没有找到请求映射,则当前的请求就会被default-servlet来处理
    -->
    <mvc:annotation-driven/>
</beans>

功能清单

功能 URL 地址 请求方式
访问首页√ / GET
查询全部数据√ /employee GET
删除√ /employee/2 DELETE
跳转到添加数据页面√ /toAdd GET
执行保存√ /employee POST
跳转到更新数据页面√ /employee/2 GET
执行更新√ /employee PUT

具体功能

访问首页

配置 view-controller 视图控制器:

<mvc:view-controller path="/" view-name="index"/>

创建页面index.html :

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" >
    <title>Title</title>
</head>
<body>
	<h1>首页</h1>  
   <a th:href="@{/employee}">访问员工信息</a>
</body>
</html>

查询所有员工数据

控制器方法:

@RequestMapping(value = "/employee", method = RequestMethod.GET)
public String getEmployeeList(Model model){
    Collection<Employee> employeeList = employee.getAll();
    model.addAttribute("employeeList", employeeList);
    return "emloyee_list";
}

创建employee_list.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Employee Info</title>
    <script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
</head>
<body>
	
    <table border="1" cellpadding="0" cellspacing="0" style="text-align: center;" id="dataTable">
        <tr>
        	<th colspan="5">Employee Info</th>
        </tr>
        <tr>
        	<th>id</th>
			<th>lastName</th>
            <th>email</th>
            <th>gender</th>
            <th>options(<a th:href="@{/toAdd}")>add</a></th>
        </tr>
        <tr th:each="employee : ${employeeList}">
        	<td th:text="${employee.id}"></td>
            <td th:text="${employee.lastName}"></td>
            <td th:text="${employee.email}"></td>
            <td th:text="${employee.gender}"></td>
            <td>
            	<a class="deleteA" @click="deleteEmployee" 
                   th:href="@{'/employee/' + ${employee.id}}">delete
                </a>
            </td>
        </tr>
    </table>
    
</body>
</html>

删除

如果要发送delete请求,就必须要满足:表单提交,请求方式post,请求参数 _method

创建处理delete请求方式的表单:

<!-- 作用:通过超链接控制表单的提交,将post请求转换为 delete 请求 -->
<form id="delete_form" method="post">
    <!-- HiddenHttpMethodFilter 要求:必须传输 _method 请求参数,并且值为最终的请求方式 -->
    <input type="hidden" name="_method" value="delete"/>
</form>

删除超链接绑定点击事件:

引入 vue.js

<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>

删除(超链接)

<a class="deleteA" @click="deleteEmployee" th:href="@{'/employee/' + ${employee.id}}">delete</a>

通过vue处理点击事件

<script type="text/javascript">
	var vue = new Vue({
        el: "#dataTable",
        methods:{
            //event表示当前事件
            deleteEmployee:function(event){
                //通过id获取表单标签
                var delete_form = document.getElementById("delete_form");
                //将出发时间的超链接的href属性为表单的action属性赋值
                delete_form.action = event.target.href;
                //提交表单
                delete_form.submit();
                //阻止超链接的默认跳转行为
                event.preventDefault();
            }
        }
    });
</script>

控制器方法:

@RequestMapping(value = "/employee/{id}", method = RequestMethod.DELETE)
public String deleteEmployee(@PathVarible("id") Integer id){
    employeeDao.delete(id);
    return "redirect:/employee";
}

跳转到添加数据页面

配置视图控制器 view-controller

springMVC.xml中:

<mvc:view-controller path="/toAdd" view-name="employee_add"></mvc:view-controller>

创建employee_add.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Add Employee</title>
</head>
<body>

<form th:action="@{/employee}" 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>
</form>

</body>
</html>

执行保存

控制器方法:

@RequestMapping(value = "/employee", method = RequestMethod.POST)
public String addEmployee(Employee employee){
    employeeDao.save(employee);
    return "redirect:/employee";
}

跳转到更新数据页面

修改(超链接)

<a th:href="@{'/employee/' + ${employee.id}}">update</a>

控制器方法:

不能写view-controller视图控制器(即springMVC.xml里面的view-controller),因为不仅要实现页面跳转,还要根据id来查询员工信息,所以一定要在控制器中写(重新查询更新后的数据)

@RequestMapping(value="/employee/{id}", method=RequestMethod.GET)
public String getEmployeeById(@PathVariable("id") Integer id, Model model){
    Employee employee = employeeDao.get(id);
    model.addAttribute("employee", employee);
    return "employee_update";
}

创建employee_update.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Update Employee</title>
</head>
<body>

<form th:action="@{/employee}" method="post">
	<input type="hidden" name="_method" value="put">
    <input type="hidden" name="id" th:value="${employee.id}">
    lastName:<input type="text" name="lastName" th:value="${employee.lastName}"> <br>
    email:<input type="text" name="email" th:value="${employee.email}"> <br>
    <!--
        th:field="${employee.gender}"可用于单选框或复选框的回显
        若单选框的value和employee.gender的值一致,则添加checked="checked"属性
    -->
    gender:<input type="radio" name="gender" value="1" th:field="${employee.gender}">male
    <input tyhpe="radio" name="gender" value="0" th:field="${employee.gender}">female
    <input type="submit" value="update"> <br>
</form>
    
</body>
</html>

执行更新

save方法先判断当前有没有这个id,如果有则直接覆盖了这个id下的员工信息

控制器方法:

@RequestMapping(value="/employee", method=RequestMethod.PUT)
public String updateEmployee(Employee employee){
    employeeDao.save(employee);
    return "redirect:/employee";
}

HttpMessageConverter

请求报文:浏览器发送到服务器,request

响应报文:服务器响应给浏览器,response

RquestEntity:请求实体,可以来接收整个请求报文,既可以接收请求头,也可以接收请求体

@RequestBody:只要把这个注解标识在控制器方法中,那这个方法的返回值就是响应报文的响应体,就是控制器方法的返回值就可以直接作为响应体响应到浏览器

HttpMessageConverter,报文信息转换器,将求报文转换为Java对象,或将Java对象转换为响应报文

HttpMessageConverter提供了两个注解和两个类型:@RequestBody(将请求报文中的请求体(请求体只有在post请求中才有,get请求中没有,因为请求体中放的就是请求参数)转换为Java数据),@ResponseBody(将java对象转换为响应体,常用)

ResponseEntity:将java数据转换为响应报文,(常用)

@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="提交"> 
</form>

控制器方法:

@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String requestBody){
    System.out.println("requestBody: " + requestBody)
    return "success";
}

输出结果:

requestBody:username=admin&password=123456

RequestEntity

RequestEntity封装请求报文的一种类型,需要在控制器方法的形参中设置该类型的形参,当前请求的请求报文就会赋值给该形参,可以通过getHeaders()获取请求头信息,通过getBody()获取请求体信息

控制器方法:

@RequestMapping("/testRequestEntity")
//这个String泛型表示 用String类型来获取请求报文
public String testRequestEntity(RequestEntity<String> requestEntity){
    //当前requestEntity表示整个报文的信息
    System.out.println("requestHeader: " + requestEntity.getHeaders());
    System.out.println("requestBody: " + requestEntity.getBody());
    return "success";
}

输出结果:

requestHeader:[host:"localhost:8080", connection:"keep-alive", content-length:"27", cache-control:"max-age=0", sec-ch-ua:"" Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"", sec-ch-ua-mobile:"?0", upgrade-insecure-requests:"1", origin:"http://localhost:8080", user-agent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"]
requestBody:username=admin&password=123

@ResponseBody

@ResponseBody用于标识一个控制器方法,可以将该方法的返回值直接作为响应报文的响应体响应到浏览器,即当前方法的返回值就是响应到浏览器的数据

@RequestMapping("/testResponseBody")
@ResponseBody
public String testResponseBody(){
    return "success";
}

结果:浏览器页面显示 success

由于 @ResponseBody 注解会将方法的返回值直接写入 HTTP 响应的正文中,因此这个方法的响应页面不会经过视图解析器的处理,也就不会经过过滤器的处理。

SpringMVC处理json

浏览器接收不了User对象,就需要将当前的用户对象转换成json类型,既要来保留User中的数据,还要正常的将其响应到浏览器中,此时的json仅仅是一个数据交换格式

@ResponseBody处理json的步骤:

在pom.xml中导入jackson的依赖:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.1</version>
</dependency>

在SpringMVC的核心配置文件中开启mvc的注解驱动:此时在HandlerAdaptor中会自动装配一个消息转换器:MappingJackson2HttpMessageConverter,可以将响应到浏览器的Java对象转换为Json格式的字符串,(注意,不是json对象,当前浏览器能够接收到浏览器中的数据就是json字符串)

<mvc:annotation-driven />

在处理器方法上使用@ResponseBody注解进行标识

将Java对象直接作为控制器方法的返回值返回,就会自动转换为json格式的字符串

@RequestMapping("/testResponseUser")
@ResponseBody
public User testResponseUser(){
    return new User(1001,"admin","123456",23,"男");
}

浏览器的页面中展示的结果:

{“id”:1001,”username”:”admin”,”password”:”123456”,”age”:23,”sex”:”男”}

以后浏览器和服务器的交互用的都是json

json对象:放在大括号内部,以键值对的格式存储数据 (对象.键 获取)

json数组:放在方括号内部,存储的是一个一个的数据 (for循环 获取)

xml 和 HTML的区别

  • xml :将整个xml当成一个document,先读根标签(即所有的标签都写在这一个标签中的这个标签就是根标签)

  • HTML:将整个HTML文档当成一个document对象,然后通过document对象来操作文档中的各个标签

SpringMVC处理ajax

ajax就是页面不刷新(不跳转)与服务器进行交互,那么现在在服务器中不能用转发和重定向,只能用响应浏览器数据(在控制器方法上加上 @ResponseBody,这个时候这个方法的返回值就可以作为响应浏览器的响应体存在)

如果不是将java对象响应到浏览器的话,那么是不需要加 jackson 的 jar包的

请求 超链接:

<div id="app">
    <a th:href="@{/testAjax}" @click="testAjax">testAjax</a>
</div>

通过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">
    var vue = new Vue({
        el:"#app",
        methods:{
            testAjax:function (event) {
                axios({
                    method:"post",
                    url:event.target.href,
                    params:{
                        username:"admin",
                        password:"123456"
                    }
                }).then(function (response) {
                    alert(response.data);
                });
                event.preventDefault();
            }
        }
    });
</script>

控制器方法:

@RequestMapping("/testAjax")
@ResponseBody
public String testAjax(String username, String password){
    System.out.println("username: " +  username + ",password: " + password);
    return "hello,ajax";
}

@RestController注解

@RestContreller是@RequestMapping在指定的请求方式下派生出来的,是来标识控制层组件的,加上这个注解,其中所有的控制器方法就相当于加上了@ResponseBody注解,那么这个方法中所有的返回值都是作为响应浏览器数据的响应体存在的

@RestController注解是springMVC提供的一个复合注解,标识在控制器的类上,就相当于为类添加了@Controller注解,并且为其中的每个方法添加了@ResponseBody注解,即 @RestController注解 = @Controller注解 + @ResponseBody注解

springboot的开发所有响应方法都需要加上responsebody注解 所以来了restcontroller注解

ResponseEntity

  • 在Java中,ResponseEntity是Spring框架中用来表示HTTP响应的实体类,它包含了HTTP响应的所有信息,包括状态码、响应头、响应体等等。

  • ResponseEntity用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文

  • ResponseEntity作为我们当前控制器方法的返回值,表示当前响应到浏览器的响应报文

  • ResponseEntity类是一个泛型类,它可以使用任意类型来表示响应体数据

文件上传和下载

从服务器将文件下载到客户端(浏览器),从客户端(浏览器)上传到服务器端,底层用的都是文件复制的功能

文件下载

@RequestMapping("/testDown")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{
    //获取ServletContext对象
    ServletContext servletContext = session.getServletContext();
    //获取服务器中文件的真实路径、部署路径,就是当前工程部署到tomcat服务器上的路径
    String realpath = servletContext.getRealPath("/static/img/1.jpg");
    //创建输入流
    InputStream is = new FileInputStream(realPath);
    //创建字节数组
    //is.available(): 来获取当前的输入流所对应的文件的所有字节数,创建这个数组的长度就是这个文件的字节数
    byte[] bytes = new byte[is.available()];
    //将流读到字节数组中,这个数组里面放的就是这个文件所对应的所有字节
    //把这个数组响应到浏览器,那这就是要下载的文件
    is.read(bytes);
    //创建HttpHeaders对象设置响应头信息,HttpHeaders:报文的头信息
    MultiValueMap<String, String> headers = new HttpHeaders();
    //设置要下载方式以及下载文件的默认文件名,设置当前的下载方式
    //attachment: 以附件的方式来下载文件
    //filename=1.jpg : 指的是下载名
    headers.add("Content-Disposition", "attachment;filename=1.jpg");
    //设置响应状态码
    HttpStatus statusCode = HttpStatus.OK;
    //创建ResponseEntity对象
    ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
    //关闭输入流
    is.close();
    return responseEntity; //包含响应体、响应头、响应状态码
}

new ResponseEntity<>(bytes, headers, statusCode):

第一个参数bytes:bytes存放着的是当前要下载的文件中所有的字节(响应体)

第二个参数headers:响应头,Map集合(不管是请求头还是响应头都是键值对)

第三个参数statusCode:响应状态码(200,404等)

响应状态码:

HttpStatus.OK             // 200 OK
HttpStatus.CREATED        // 201 Created
HttpStatus.NO_CONTENT     // 204 No Content
HttpStatus.BAD_REQUEST    // 400 Bad Request
HttpStatus.UNAUTHORIZED   // 401 Unauthorized
HttpStatus.NOT_FOUND      // 404 Not Found
HttpStatus.INTERNAL_SERVER_ERROR  // 500 Internal Server Error

文件上传

文件上传要求form表单的请求方式必须为post,并且添加属性enctype=”multipart/form-data”

enctype默认属性:application/x-www-form-urlencoded,如果要实现上传功能,需要是multipart/form-data,这个时候我们才能接收到文件,就是多段数据,以二进制流的形式传送过去。

其中的type=”file” :浏览器解析之后,会显示一个框,可以选择文件

<form th:action="@{/testUp}" method="post" enctype="multipart/form-data">
    头像:<input type="file" name="photo"> <br>
    <input type="submit" value="上传">
</form>

SpringMVC中将上传的文件封装到 MultipartFile对象中,通过次对象可以获取文件相关信息

上传步骤:

添加依赖:

<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

在SpringMVC的配置文件中添加配置:

在springMVC中,把当前上传的文件封装到了一个MultipartFile对象中,这个对象把我们当前上传的文件所包含的信息和我们要做的操作都封装好了。我们上传的对象不能直接转换成MultipartFile对象,必须要在springMVC.xml中设置一个文件上传解析器

这个bean我们不访问,由springMVC的 IoC 容器自动访问它来实现访问的过程。springMVC.xml中:

<!--必须通过文件解析器的解析才能将文件转换为MultipartFile对象-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

控制器方法:

@RequestMapping("/testUp")
//获取服务器路径需要有session
public String testUp(MultipartFile photo, HttpSession session) throws IOException {
    //获取上传的文件的文件名
    String fileName = photo.getOriginalFilename();
    //处理文件重名问题
    //获取这个文件名的后缀(最后一个点出现的地方)
    String hzName = fileName.substring(fileName.lastIndexOf(".")); //(.jpg或者.png等等)
    //将UUID和后缀名拼接后的结果作为最终的文件名
    fileName = UUID.randomUUID().toString() + hzName;
    //获取服务器中photo目录的路径
    ServletContext servletContext = session.getServletContext();
    String photoPath = servletContext.getRealPath("photo"); //放在服务器路径下的photo路径下(上传的位置)
   	//如果这个路径不存在,则创建目录
    File file = new File(photoPath);
    //判断photoPath所对应路径是否存在,如果不存在则创建目录
    if(!file.exists()){
        file.mkdir();
    }
    //确定最终文件上传的路径:photoPath + 文件分隔符、路径分隔符 + 上传文件的名字
    String finalPath = photoPath + File.separator + fileName;
    //实现上传功能
    //transferTo()这个方法里面封装的就是先读再写,将这个文件放在finalPath这个路径下
    photo.transferTo(new File(finalPath));
    return "success";
}

photo封装了当前上传的文件和信息

photo.getName() 获取的是当前表单的name属性值(photo)

photo.getOriginalFilename() 获取的是当前我们上传的文件的名字

photo.transferTo() :可以将我们当前资源转移,现在是上传文件,可以将浏览器上传的文件转移到服务器中,参数是转移到哪儿

如果上传的文件和这个文件夹中的其他文件重名了,则会覆盖这个文件夹中的文件,这时候需要对上传的文件名进行处理,将这个名字用UUID来代替,但是它的后缀还需要保留

获取UUID:String uuid = UUID.randomUUID().toString();

将UUID中的 - 替换为空字符串: String uuid = UUID.randomUUID().toString().replaceAll("-", "");

测试

测试文件上传和下载 file.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>测试文件上传和下载</title>
</head>
<body>
    <a th:href="@{/testDown}">下载1.jpg</a>  <br>
    <form th:action="@{/testUp}" method="post" ectype="multipart/form-data">
        头像: <input type="file" name="photo"> <br>
        <input type="submit" value="上传">
    </form>
</body>
</html>

拦截器

过滤器作用在浏览器到DispacterServlet之间的,DispacterServlet接收到请求后会对请求进行处理,根据当前的请求信息去跟RequestMapping(请求映射)进行匹配,找到了相对应的请求映射, 那请求映射所对应的控制器方法就是我们处理请求的方法。DispacterServlet会调用Controller

拦截器的配置

SpringMVC中的拦截器用于拦截控制器方法的执行,

SpringMVC中的拦截器需要实现 HandlerInterceptor

SpringMVC的拦截器必须在SpringMVC的配置文件中进行配置:

<bean class="com.byxl8112.interceptor.Firstinterceptor"></bean>
<ref bean="firstInterceptor"></ref> 
<!-- 以上两种配置方式都是对DispatcherServlet所处理的所有的请求进行拦截,只有DispatcherServlet能处理的请求才会对应控制器方法,才能被拦截器拦截 -->
<mvc:interceptor>
    <mvc:mapping path="/**"/>
    <mvc:exclude-mapping path="/testRequestEntity"/>
    <ref bean="firstInterceptor"></ref>
</mvc:interceptor>
<!-- 
	以上配置方式可以通过ref或bean标签设置拦截器,通过mvc:mapping设置需要拦截的请求,通过mvc:exclude-mapping设置需要排除的请求,即不需要拦截的请求
-->

拦截器的三个抽象方法

拦截器作用于控制器执行的前后端,拦截控制器方法

实现 HandlerInterceptor 接口

SpringMVC中的拦截器有三个抽象方法:

  • preHandle:控制器(处理器)方法执行之前执行 preHandle(),其boolean类型的返回值表示是否拦截或放行,返回true为放行,即调用控制器方法;返回false表示拦截,即不调用控制器方法
  • postHandle:控制器方法执行之后执行 postHandle()
  • afterComplation:处理完视图和模型数据,渲染视图(将模型数据填充到视图中为用户展示数据)完毕之后执行 afterComplation()

多个拦截器的执行顺序

按照配置顺序来起作用,越靠后配置的拦截器,越贴近控制器方法

若每个拦截器的 preHandle() 都返回true:

  • 此时多个拦截器的执行顺序和拦截器在SpringMVC的配置文件的配置顺序有关:
  • preHandle() 会按照配置的顺序执行,而 postHandler() 和 afterComplation() 会按照配置的反序执行
<mvc:interceptors>        
	<ref bean="firstInterceptor"/>
    <ref bean="secondInterceptor"/>
</mvc:interceptors>

执行结果:

FirstInterceptor--->preHandle
SecondInterceptor--->preHandle
SecondInterceptor--->postHandle
FirstInterceptor--->postHandle
SecondInterceptor--->afterHandle
FirstInterceptor--->afterHandle

若某个拦截器的preHandler()返回了false:

  • preHandle() 返回 false 的拦截器和它之前的拦截器的 preHandle() 都会执行,postHandle() 都不执行,返回false的拦截器之前的拦截器的 afterComplation() 会执行,因为它是根据索引执行的,而索引最大等于返回 false 之前的拦截器的索引

  • preHandle 会执行到返回 false 的这个拦截器,post一个都不会执行,after completion 会从成功放行的拦截器逆序执行

    其中的视图控制器也会被拦截器拦截:即

    <mvc:view-controller path="/" view-name="index"/>

拦截器测试

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.byxl8112.mvc"/>

    <!--配置视图解析器-->
    <!--配置Thymeleaf视图解析器-->
    <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:view-controller path="/" view-name="index"/>

    <mvc:default-servlet-handler />

    <!--开启mvc的注解驱动-->
    <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>

    <!--配置文件上传解析器,将上传的文件封装为MultipartFile-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

    <!--配置拦截器,bean表示当前的某一个类型的对象就是一个拦截器-->
    <mvc:interceptors>
        <!--以下两种方式默认对所有请求进行拦截-->
<!--        <bean class="com.byxl8112.mvc.interceptors.FirstInterceptor"/>-->
        <!--需要将拦截器纳入IoC容器进行配置-->
<!--        <ref bean="firstInterceptor"/>-->

        <!--以下这种方式可以设置当前的拦截路径-->
       <!-- <mvc:interceptor>
            <mvc:mapping path="/**"/>   	拦截所有路径,包括后面的所有路径
            <mvc:exclude-mapping path="/"/>    拦截所有路径,除了主页面
            <ref bean="firstInterceptor"/>
        </mvc:interceptor> -->

        <ref bean="firstInterceptor"/>
        <ref bean="secondInterceptor"/>
    </mvc:interceptors>
</beans>

interceptors包下的FirstInterceptor.java类:

@Component
public class FirstInterceptor implements HandlerInterceptor {

    @Override
    //boolean类型表示是否放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("FirstInterceptor--->preHandle");

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        System.out.println("FirstInterceptor--->postHandle");

        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        System.out.println("FirstInterceptor--->afterHandle");

        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}

interceptors包下的SecondInterceptor.java类:

@Component
public class SecondInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("SecondInterceptor--->preHandle");
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("SecondInterceptor--->postHandle");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("SecondInterceptor--->afterHandle");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}

controller包下的TestController.java类:

@Controller
public class TestController {
    
    // ** : 表示一层或多层目录
    @RequestMapping("/**/testInterceptor")
    public String testInterceptor(){
        return "success";
    }
    
}

index.html

<a th:href="@{/testInterceptor}">测试拦截器</a>

异常处理器

基于配置的异常处理

SpringMVC提供了一个处理控制器方法执行过程中所出现的异常的接口(解析器):HandlerExceptionResolver

HandlerExceptionResolver接口的实现类有:DefaultHandlerExceptionResolver(SpringMVC默认使用的异常处理器)和SimpleMappingExceptionResolver(自定义异常处理,如果当前的控制器方法在执行的过程中出现了某些异常,我们可以指定一个视图让他进行跳转)

SpringMVC提供了自定义的异常处理器SimpleMappingExceptionResolver,使用方式:

springMVC.xml中:

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
        	<!--
        		properties的键表示处理器方法执行过程中出现的异常
        		properties的值表示若出现指定异常时,设置一个新的视图名称,跳转到指定页面
        	-->
            <prop key="java.lang.ArithmeticException">error</prop>
        </props>
    </property>
    <!--
    	exceptionAttribute属性设置一个属性名,将出现的异常信息在请求域中进行共享
    -->
    <property name="exceptionAttribute" value="ex"></property>
</bean>

基于注解的异常处理

controller包下的ExceptionController.java类:

//@ControllerAdvice将当前类标识为异常处理的组件
//这个注解是@Component的扩展注解,也有将类表示为组件的功能
@ControllerAdvice
public class ExceptionController {

    //@ExceptionHandler用于设置所标识方法处理的异常
    //这个注解所标识的方法来作为我们当前新的控制器方法来执行,如果出现了value的这些异常,然后就会执行当前的方法作为新的控制器方法
    @ExceptionHandler(ArithmeticException.class)
    //ex表示当前请求处理中出现的异常对象
    public String handleArithmeticException(Exception ex, Model model){
        model.addAttribute("ex", ex);
        return "error";
    }
}

error.html中

<body>
    出现错误
    <p th:text="${ex}"></p>
</body>

index.html中

<a th:href="@{/testExceptionHandler}">测试异常处理</a>

controller包下的TestController.java类:

@Controller
public class TestController {

    //配置异常处理
    @RequestMapping("/testExceptionHandler")
    public String testExceptionHandler(){
        System.out.println(1/0);  //异常
        return "success";
    }
}

注解配置SpringMVC

每当启动tomcat服务器,第一个要加载的配置文件就是 web.xml

使用配置类(创建Configration.java类来代替spring.xml)和注解代替web.xml(web工程的描述符)和SpringMVC 配置文件的功能

创建初始化类,代替web.xml

在Servlet3.0环境中,容器会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类,如果找到的话就用它来配置Servlet容器(Tomcat服务器)。

Spring提供了这个接口的实现,名为SpringServletContainerInitializer,这个类反过来又会查找实现WebApplicationInitializer的类并将配置的任务交给它们来完成。Spring3.2引入了一个便利的WebApplicationInitializer基础实现,名为AbstractAnnotationConfigDispatcherServletInitializer,当我们的类扩展了AbstractAnnotationConfigDispatcherServletInitializer并将其部署到Servlet3.0容器的时候,容器会自动发现它,并用它来配置Servlet上下文。

//这个类用来代替 web.xml 文件
//这个类也是会在服务器启动时自动加载的
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {

    /**
     * 指定spring的配置类
     * @return
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    /**
     * 指定SpringMVC的配置类
     * @return
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    /**
     * 指定DispatcherServlet的映射规则,即url-pattern
     * getServletMappings(): 就是来获取当前DispatcherServlet的映射路径,即url-pattern
     * @return
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    /**
     * 添加过滤器
     * @return
     */
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        //设置初始化 参数
        encodingFilter.setEncoding("UTF-8");
        encodingFilter.setForceRequestEncoding(true);
        HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
        return new Filter[]{encodingFilter, hiddenHttpMethodFilter};
    }
}

创建SpringConfig配置类,代替spring的配置文件

@Configuration
public class SpringConfig{
    //sss整合之后,spring的配置信息写在此类中
}

创建WebConfig配置类,代替SpringMVC的配置文件

WebMvcConfigurer是一个接口,用于配置全局的SpringMVC的相关属性,采用JAVABEAN的方式来代替传统的XML配置文件,提供了跨域设置、静态资源处理器、类型转化器、自定义拦截器、页面跳转等能力。这个接口

@Configuration
//扫描组件
@ComponentScan("com.atguigu.mvc.controller")
//开启MVC注解驱动
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    //使用默认的servlet处理静态资源
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    //配置文件上传解析器
    @Bean
    public CommonsMultipartResolver multipartResolver(){
        return new CommonsMultipartResolver();
    }

    //配置拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        FirstInterceptor firstInterceptor = new FirstInterceptor();
        //  /** 指的是任意一层所有请求
        registry.addInterceptor(firstInterceptor).addPathPatterns("/**");
    }
    
    //配置视图控制view-controller
    
    /*@Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
    }*/
    
    //配置异常映射
    /*@Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();
        // Properties 主要来操作属性级properties文件的,文件中存储的键和值都是字符串,只能操作字符串的键和值
        // Properties 来操作属性级文件(properties文件)的时候是不允许使用put方法和get方法的
        // getProperties()  : 来获取某一个键所对应的值
        // setProperties()  : 来为当前的properties设置键值对
        Properties prop = new Properties();
        //
        prop.setProperty("java.lang.ArithmeticException", "error");
        //设置异常映射,
        exceptionResolver.setExceptionMappings(prop);
        //设置共享异常信息的键,可以从请求域中获取异常信息了
        exceptionResolver.setExceptionAttribute("ex");
        resolvers.add(exceptionResolver);
    }*/
    
	//必须是符合自动装配的规则的,
    //配置生成模板解析器
    @Bean
    public ITemplateResolver templateResolver() {
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        // ServletContextTemplateResolver需要一个ServletContext作为构造参数,可通过WebApplicationContext 的方法获得
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(
                webApplicationContext.getServletContext());
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        return templateResolver;
    }

    //参数:必须是符合自动装配赋值的规则的,这里的参数必须是当前的Spring IoC容器中所拥有的这个bean,这个时候这个bean能为这个参数赋值的情况下,才能加这个参数
    //生成模板引擎并为模板引擎注入模板解析器
    @Bean
    public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        return templateEngine;
    }

    //生成视图解析器并未解析器注入模板引擎
    @Bean
    public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setCharacterEncoding("UTF-8");
        viewResolver.setTemplateEngine(templateEngine);
        return viewResolver;
    }
}

测试功能

@RequestMapping("/")
public String index(){
    return "index";
}

SpringMVC执行流程

创建所需的对象、执行拦截器preHandle()、执行处理器方法、执行拦截器postHandle()、处理模型数据渲染视图、执行拦截器afterCompletion()

SpringMVC常用组件

  • DispatcherServlet:前端控制器,不需要工程师开发,由框架提供

作用:统一处理请求和响应,整个流程控制的中心,由它调用其它组件处理用户的请求

  • HandlerMapping:处理器(控制器)映射器,不需要工程师开发,由框架提供,将请求和控制器创建关联,如果当前的请求和请求映射能够匹配成功,那么当前的控制器方法就是处理请求的方法

作用:根据请求的url、method等信息查找Handler(Controller),即控制器方法,将请求和控制器方法进行映射

  • Handler:处理器,需要工程师开发

作用:在DispatcherServlet的控制下Handler对具体的用户请求进行处理,由它来控制各个组件来帮助我们来处理请求

  • HandlerAdapter:处理器适配器,不需要工程师开发,由框架提供

作用:通过HandlerAdapter对处理器(控制器方法)进行执行 ,来调用控制器方法的

  • ViewResolver:视图解析器,不需要工程师开发,由框架提供

视图解析器可以根据不同的视图创建不同的视图来进行页面渲染

作用:进行视图解析,得到相应的视图,例如:ThymeleafView、InternalResourceView、RedirectView

  • View:视图,不需要工程师开发,由框架或视图技术提供

作用:将模型数据通过页面展示给用户,当视图渲染完毕之后,将当前的数据为用户进行展示

DispatcherServlet初始化过程

DispatcherServlet 本质上是一个 Servlet,所以天然的遵循 Servlet 的生命周期。所以宏观上是 Servlet 生命周期来进行调度。

image-20230628202431359

初始化WebApplicationContext

所在类:org.springframework.web.servlet.FrameworkServlet

protected WebApplicationContext initWebApplicationContext() {
    WebApplicationContext rootContext =
        WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    WebApplicationContext wac = null;

    if (this.webApplicationContext != null) {
        // A context instance was injected at construction time -> use it
        wac = this.webApplicationContext;
        if (wac instanceof ConfigurableWebApplicationContext) {
            ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
            if (!cwac.isActive()) {
                // The context has not yet been refreshed -> provide services such as
                // setting the parent context, setting the application context id, etc
                if (cwac.getParent() == null) {
                    // The context instance was injected without an explicit parent -> set
                    // the root application context (if any; may be null) as the parent
                    cwac.setParent(rootContext);
                }
                configureAndRefreshWebApplicationContext(cwac);
            }
        }
    }
    if (wac == null) {
        // No context instance was injected at construction time -> see if one
        // has been registered in the servlet context. If one exists, it is assumed
        // that the parent context (if any) has already been set and that the
        // user has performed any initialization such as setting the context id
        wac = findWebApplicationContext();
    }
    if (wac == null) {
        // No context instance is defined for this servlet -> create a local one
        // 创建WebApplicationContext
        wac = createWebApplicationContext(rootContext);
    }

    if (!this.refreshEventReceived) {
        // Either the context is not a ConfigurableApplicationContext with refresh
        // support or the context injected at construction time had already been
        // refreshed -> trigger initial onRefresh manually here.
        synchronized (this.onRefreshMonitor) {
            // 刷新WebApplicationContext
            onRefresh(wac);
        }
    }

    if (this.publishContext) {
        // Publish the context as a servlet context attribute.
        // 将IOC容器在应用域共享
        String attrName = getServletContextAttributeName();
        getServletContext().setAttribute(attrName, wac);
    }

    return wac;
}

创建WebApplicationContext

所在类:org.springframework.web.servlet.FrameworkServlet

protected WebApplicationContext createWebApplicationContext(@Nullable ApplicationContext parent) {
    Class<?> contextClass = getContextClass();
    if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
        throw new ApplicationContextException(
            "Fatal initialization error in servlet with name '" + getServletName() +
            "': custom WebApplicationContext class [" + contextClass.getName() +
            "] is not of type ConfigurableWebApplicationContext");
    }
    // 通过反射创建 IOC 容器对象
    ConfigurableWebApplicationContext wac =
        (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

    wac.setEnvironment(getEnvironment());
    // 设置父容器
    wac.setParent(parent);
    String configLocation = getContextConfigLocation();
    if (configLocation != null) {
        wac.setConfigLocation(configLocation);
    }
    configureAndRefreshWebApplicationContext(wac);

    return wac;
}

DispatcherServlet初始化策略

FrameworkServlet创建WebApplicationContext后,刷新容器,调用onRefresh(wac),此方法在DispatcherServlet中进行了重写,调用了initStrategies(context)方法,初始化策略,即初始化DispatcherServlet的各个组件

所在类:org.springframework.web.servlet.DispatcherServlet

protected void initStrategies(ApplicationContext context) {
   initMultipartResolver(context);
   initLocaleResolver(context);
   initThemeResolver(context);
   initHandlerMappings(context);
   initHandlerAdapters(context);
   initHandlerExceptionResolvers(context);
   initRequestToViewNameTranslator(context);
   initViewResolvers(context);
   initFlashMapManager(context);
}

DispatcherServlet调用组件处理请求

processRequest()

FrameworkServlet重写HttpServlet中的service()和doXxx(),这些方法中调用了processRequest(request, response)

所在类:org.springframework.web.servlet.FrameworkServlet

protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    long startTime = System.currentTimeMillis();
    Throwable failureCause = null;

    LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
    LocaleContext localeContext = buildLocaleContext(request);

    RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);

    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());

    initContextHolders(request, localeContext, requestAttributes);

    try {
		// 执行服务,doService()是一个抽象方法,在DispatcherServlet中进行了重写
        doService(request, response);
    }
    catch (ServletException | IOException ex) {
        failureCause = ex;
        throw ex;
    }
    catch (Throwable ex) {
        failureCause = ex;
        throw new NestedServletException("Request processing failed", ex);
    }

    finally {
        resetContextHolders(request, previousLocaleContext, previousAttributes);
        if (requestAttributes != null) {
            requestAttributes.requestCompleted();
        }
        logResult(request, response, failureCause, asyncManager);
        publishRequestHandledEvent(request, response, startTime, failureCause);
    }
}

doService()

所在类:org.springframework.web.servlet.DispatcherServlet

@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
    logRequest(request);

    // Keep a snapshot of the request attributes in case of an include,
    // to be able to restore the original attributes after the include.
    Map<String, Object> attributesSnapshot = null;
    if (WebUtils.isIncludeRequest(request)) {
        attributesSnapshot = new HashMap<>();
        Enumeration<?> attrNames = request.getAttributeNames();
        while (attrNames.hasMoreElements()) {
            String attrName = (String) attrNames.nextElement();
            if (this.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) {
                attributesSnapshot.put(attrName, request.getAttribute(attrName));
            }
        }
    }

    // Make framework objects available to handlers and view objects.
    request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());
    request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
    request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);
    request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());

    if (this.flashMapManager != null) {
        FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response);
        if (inputFlashMap != null) {
            request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));
        }
        request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
        request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager);
    }

    RequestPath requestPath = null;
    if (this.parseRequestPath && !ServletRequestPathUtils.hasParsedRequestPath(request)) {
        requestPath = ServletRequestPathUtils.parseAndCache(request);
    }

    try {
        // 处理请求和响应
        doDispatch(request, response);
    }
    finally {
        if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
            // Restore the original attribute snapshot, in case of an include.
            if (attributesSnapshot != null) {
                restoreAttributesAfterInclude(request, attributesSnapshot);
            }
        }
        if (requestPath != null) {
            ServletRequestPathUtils.clearParsedRequestPath(request);
        }
    }
}

doDispatch()

所在类:org.springframework.web.servlet.DispatcherServlet

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpServletRequest processedRequest = request;
    HandlerExecutionChain mappedHandler = null;
    boolean multipartRequestParsed = false;

    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);

    try {
        ModelAndView mv = null;
        Exception dispatchException = null;

        try {
            processedRequest = checkMultipart(request);
            multipartRequestParsed = (processedRequest != request);

            // Determine handler for the current request.
            /*
            	mappedHandler:调用链
                包含handler、interceptorList、interceptorIndex
            	handler:浏览器发送的请求所匹配的控制器方法
            	interceptorList:处理控制器方法的所有拦截器集合
            	interceptorIndex:拦截器索引,控制拦截器afterCompletion()的执行
            */
            mappedHandler = getHandler(processedRequest);
            if (mappedHandler == null) {
                noHandlerFound(processedRequest, response);
                return;
            }

            // Determine handler adapter for the current request.
           	// 通过控制器方法创建相应的处理器适配器,调用所对应的控制器方法
            HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());

            // Process last-modified header, if supported by the handler.
            String method = request.getMethod();
            boolean isGet = "GET".equals(method);
            if (isGet || "HEAD".equals(method)) {
                long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
                if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
                    return;
                }
            }
			
            // 调用拦截器的preHandle()
            if (!mappedHandler.applyPreHandle(processedRequest, response)) {
                return;
            }

            // Actually invoke the handler.
            // 由处理器适配器调用具体的控制器方法,最终获得ModelAndView对象
            mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

            if (asyncManager.isConcurrentHandlingStarted()) {
                return;
            }

            applyDefaultViewName(processedRequest, mv);
            // 调用拦截器的postHandle()
            mappedHandler.applyPostHandle(processedRequest, response, mv);
        }
        catch (Exception ex) {
            dispatchException = ex;
        }
        catch (Throwable err) {
            // As of 4.3, we're processing Errors thrown from handler methods as well,
            // making them available for @ExceptionHandler methods and other scenarios.
            dispatchException = new NestedServletException("Handler dispatch failed", err);
        }
        // 后续处理:处理模型数据和渲染视图
        processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
    }
    catch (Exception ex) {
        triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
    }
    catch (Throwable err) {
        triggerAfterCompletion(processedRequest, response, mappedHandler,
                               new NestedServletException("Handler processing failed", err));
    }
    finally {
        if (asyncManager.isConcurrentHandlingStarted()) {
            // Instead of postHandle and afterCompletion
            if (mappedHandler != null) {
                mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
            }
        }
        else {
            // Clean up any resources used by a multipart request.
            if (multipartRequestParsed) {
                cleanupMultipart(processedRequest);
            }
        }
    }
}

processDispatchResult()

private void processDispatchResult(HttpServletRequest request, HttpServletResponse response,
                                   @Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv,
                                   @Nullable Exception exception) throws Exception {

    boolean errorView = false;

    if (exception != null) {
        if (exception instanceof ModelAndViewDefiningException) {
            logger.debug("ModelAndViewDefiningException encountered", exception);
            mv = ((ModelAndViewDefiningException) exception).getModelAndView();
        }
        else {
            Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
            mv = processHandlerException(request, response, handler, exception);
            errorView = (mv != null);
        }
    }

    // Did the handler return a view to render?
    if (mv != null && !mv.wasCleared()) {
        // 处理模型数据和渲染视图
        render(mv, request, response);
        if (errorView) {
            WebUtils.clearErrorRequestAttributes(request);
        }
    }
    else {
        if (logger.isTraceEnabled()) {
            logger.trace("No view rendering, null ModelAndView returned.");
        }
    }

    if (WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
        // Concurrent handling started during a forward
        return;
    }

    if (mappedHandler != null) {
        // Exception (if any) is already handled..
        // 调用拦截器的afterCompletion()
        mappedHandler.triggerAfterCompletion(request, response, null);
    }
}

SpringMVC的执行流程

  1. 用户向服务器发送请求,请求被SpringMVC 前端控制器 DispatcherServlet捕获。

  2. DispatcherServlet对请求URL进行解析,得到请求资源标识符(URI),判断请求URI对应的映射:

情况1:不存在

i. 再判断是否配置了 mvc:default-servlet-handler (默认servlet处理静态资源)

ii. 如果没配置,则控制台报映射查找不到,客户端展示404错误

image-20230628203109756

情况2:存在,则执行下面的流程

  1. 根据该URI,调用HandlerMapping获得该Handler配置的所有相关的对象(包括Handler对象以及Handler对象对应的拦截器)(控制器方法、拦截器集合、拦截器索引),最后以HandlerExecutionChain执行链对象的形式返回。

  2. DispatcherServlet 根据获得的Handler,选择一个合适的HandlerAdapter。(HandlerAdapter也是有各种不同的类型的(比如说requestMappingHandlerAdapter))

  3. 如果成功获得HandlerAdapter,此时将开始执行拦截器的preHandler(…)方法【正向】(限制性preHandler,再通过HandlerAdapter去调用控制器方法Handler)

  4. 提取Request中的模型数据,填充Handler入参,开始执行Handler(Controller)方法,处理请求。在填充Handler的入参过程中,根据你的配置,Spring将帮你做一些额外的工作:

a) HttpMessageConveter: 将请求消息(如Json、xml等数据)转换成一个对象,将对象转换为指定的响应信息

​ 两个注解和两个类型(@RequestBody、@ResponseBody、RequestEntity、ResposneEntity),请求是将请求报文信息转换成java对象,响应是将java对象转换成响应报文

b) 数据转换:对请求消息进行数据转换。如String转换成Integer、Double等

c) 数据格式化:对请求消息进行数据格式化。 如将字符串转换成格式化数字或格式化日期等,

d) 数据验证: 验证数据的有效性(长度、格式等),验证结果存储到BindingResult或Error中,(就是来验证长度、格式是否符合规则),可以放在客户端来验证。

  1. Handler执行完成后,向DispatcherServlet 返回一个ModelAndView对象。

  2. 此时将开始执行拦截器的postHandle(…)方法【逆向】。

  3. 根据返回的ModelAndView(此时会判断是否存在异常:如果存在异常,则执行HandlerExceptionResolver进行异常处理)选择一个适合的ViewResolver进行视图解析,根据Model和View,来渲染视图。

    ViewResolver:不加前缀 -> thymeleaf ViewResovler;forward:前缀 -> internalResource ViewResolver;redirect: 前缀 -> RedirectView ViewResolver

  4. 渲染视图完毕执行拦截器的afterCompletion(…)方法【逆向】。

  5. 将渲染结果返回给客户端。