⭐表示重要。

第一章:概述

  • SpringMVC 将『把请求参数注入到POJO对象』这个操作称为『数据绑定』,英文单词是 binding。
  • 数据类型的转换和格式化就发生在数据绑定的过程中,数据类型的转换和格式化是密不可分的两个过程,很多带格式化的数据必须明确的指定格式之后才能进行数据类型转换,最典型的就是『日期类型』。

第二章:自动类型转换

  • HTTP 协议是一个无类型的协议,我们在服务器端接收到请求参数等形式的数据的时候,本质上都是字符串类型,参考 javax.servlet.ServletRequest 接口中获取全部请求参数的方法:
  1. public Map<String, String[]> getParameterMap();
  • 但是,在我们的实体类对象中需要的类型非常丰富,因此,SpringMVC 对基本数据类型提供了自动的类型转换。例如:请求参数是 "100" 字符串,我们实体类中需要的是 Integer 类型,那么 SpringMVC 会自动将字符串转换为 Integer 类型注入实体类。

第三章:日期和数值类型(⭐)

3.1 概述

  • SpringMVC 提供了 @DateTimeFormat 注解和 @NumberFormat 注解实现了在入参格式化场景下将 字符串 转换为 日期类型数值类型
  • SpringMVC 提供了 @JsonFormat 注解实现 了在出参格式化场景下将 日期类型 转换为 字符串 ,需要 jackson 的支持。

3.2 日期和数值类型的使用

  • ① 实体类:
  1. package com.github.fairy.era.mvc.entity;
  2. import org.springframework.format.annotation.DateTimeFormat;
  3. import org.springframework.format.annotation.NumberFormat;
  4. import java.io.Serializable;
  5. import java.util.Date;
  6. /**
  7. * @author 许大仙
  8. * @version 1.0
  9. * @since 2021-11-16 10:12
  10. */
  11. public class Product implements Serializable {
  12. // 通过注解设定数据格式
  13. @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  14. private Date productDate;
  15. // 通过注解设定数据格式
  16. @NumberFormat(pattern = "###,###,###.###")
  17. private Double productPrice;
  18. public Date getProductDate() {
  19. return productDate;
  20. }
  21. public void setProductDate(Date productDate) {
  22. this.productDate = productDate;
  23. }
  24. public Double getProductPrice() {
  25. return productPrice;
  26. }
  27. public void setProductPrice(Double productPrice) {
  28. this.productPrice = productPrice;
  29. }
  30. @Override
  31. public String toString() {
  32. return "Product{" +
  33. "productDate=" + productDate +
  34. ", productPrice=" + productPrice +
  35. '}';
  36. }
  37. }
  • ② 表单:
  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>首页</title>
  6. </head>
  7. <body>
  8. <form method="post" th:action="@{/save/product}">
  9. 生产日期:<input name="productDate" type="text" value="1992-10-15 17:15:06"/><br/>
  10. 产品价格:<input name="productPrice" type="text" value="111,222,333.444"/><br/>
  11. <button type="submit">保存</button>
  12. </form>
  13. </body>
  14. </html>
  • ③ handler 方法:
  1. package com.github.fairy.era.mvc.handler;
  2. import com.github.fairy.era.mvc.entity.Product;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.PostMapping;
  7. /**
  8. * @author 许大仙
  9. * @version 1.0
  10. * @since 2021-11-16 10:46
  11. */
  12. @Controller
  13. public class ProductHandler {
  14. private final Logger logger = LoggerFactory.getLogger(this.getClass());
  15. @PostMapping("/save/product")
  16. public String saveProduct(Product product) {
  17. logger.info("ProductHandler.saveProduct的请求参数{}", product);
  18. return "target";
  19. }
  20. }

3.3 转换失败后的处理方式

3.3.1 默认结果

SpringMVC类型转换失败后的默认结果.png

  • 实际开发中,当然不能将错误抛给用户。

3.3.2 BindingResult 接口

BindingResult接口.png

  • BindingResult 接口和其父接口 Errors 中定义了很多和数据绑定相关的方法,如果在数据绑定过程中发生了错误,那么就可以通过这个接口类型的对象获取到相关的错误信息。

3.3.3 重构 handler 方法

  1. package com.github.fairy.era.mvc.handler;
  2. import com.github.fairy.era.mvc.entity.Product;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.validation.BindingResult;
  7. import org.springframework.validation.FieldError;
  8. import org.springframework.web.bind.annotation.PostMapping;
  9. import org.springframework.web.bind.annotation.ResponseBody;
  10. import java.util.Optional;
  11. import java.util.stream.Collectors;
  12. /**
  13. * @author 许大仙
  14. * @version 1.0
  15. * @since 2021-11-16 10:46
  16. */
  17. @Controller
  18. public class ProductHandler {
  19. private final Logger logger = LoggerFactory.getLogger(this.getClass());
  20. @PostMapping("/save/product")
  21. @ResponseBody
  22. public String saveProduct(Product product,
  23. // 在实体类参数和 BindingResult 之间不能有任何其他参数
  24. // 封装数据绑定结果的对象
  25. BindingResult result) {
  26. // 如果数据绑定过程中发生了错误
  27. if (result.hasErrors()) {
  28. // 如果发生了错误,就跳转到专门显示错误信息的页面
  29. // 相关的错误信息会自动放到请求域中,当然,也可以手动获取
  30. String errorMessage = Optional.ofNullable(result.getFieldError()).map(FieldError::getDefaultMessage).stream().collect(Collectors.joining(","));
  31. logger.error("ProductHandler.saveProduct.errorMessage = {}", errorMessage);
  32. return "error";
  33. }
  34. logger.info("ProductHandler.saveProduct的请求参数是{}", product);
  35. return "target";
  36. }
  37. }

3.3.4 在页面上显示错误消息

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>错误页面</title>
  6. </head>
  7. <body>
  8. <!-- th:errors 属性:用来显示请求处理过程中发生的错误 -->
  9. <!-- th:errors 属性值:访问错误信息的表达式 -->
  10. <!-- 访问错误信息的表达式:访问请求域,需要使用 ${} 格式 -->
  11. <!-- 访问请求域使用的属性名:执行数据绑定的实体类的简单类名首字母小写 -->
  12. <!-- 具体错误信息:找到实体类之后进一步访问出问题的属性名 -->
  13. <p th:errors="${product.productDate}">这里显示具体错误信息</p>
  14. </body>
  15. </html>

第四章:自定义类型转换器

4.1 概述

  • 在实际开发过程中,难免会出现某些情况需要自定义类型转换器,因为我们自己自定义的类型在 SpringMVC 中没有对应的内置类型转换器,此时需要我们提供自定义类型转换器来执行转换。

4.2 需求

  • 希望将表单中的 aaa,bbb,ccc 封装到实体类对象 Student 中的 address属性中。

4.3 创建实体类

  • 实体类 Student 中有一个属性 address,其类型为 Address 。

  • 示例:

  • Address.java
  1. package com.github.fairy.era.mvc.entity;
  2. /**
  3. * @author 许大仙
  4. * @version 1.0
  5. * @since 2021-11-16 13:36
  6. */
  7. public class Address {
  8. /**
  9. * 省份
  10. */
  11. private String province;
  12. /**
  13. * 城市
  14. */
  15. private String city;
  16. /**
  17. * 街道
  18. */
  19. private String street;
  20. public String getProvince() {
  21. return province;
  22. }
  23. public void setProvince(String province) {
  24. this.province = province;
  25. }
  26. public String getCity() {
  27. return city;
  28. }
  29. public void setCity(String city) {
  30. this.city = city;
  31. }
  32. public String getStreet() {
  33. return street;
  34. }
  35. public void setStreet(String street) {
  36. this.street = street;
  37. }
  38. }
  • Student.java
  1. package com.github.fairy.era.mvc.entity;
  2. /**
  3. * @author 许大仙
  4. * @version 1.0
  5. * @since 2021-11-16 13:36
  6. */
  7. public class Student {
  8. private Address address;
  9. public Address getAddress() {
  10. return address;
  11. }
  12. public void setAddress(Address address) {
  13. this.address = address;
  14. }
  15. @Override
  16. public String toString() {
  17. return "Student{" +
  18. "address=" + address +
  19. '}';
  20. }
  21. }

4.4 表单

  • 希望通过一个文本输入约定指定格式的字符串,然后转换为我们需要的类型,此时就必须通过自定义类型转换器来实现,因为 SpringMVC 内部没有这样的类型转换器。

  • 示例:

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>首页</title>
  6. </head>
  7. <body>
  8. <h3>自定义类型转换器</h3>
  9. <form method="post" th:action="@{/save/student}">
  10. 地址:<input name="address" type="text" value="aaa,bbb,ccc"/><br/>
  11. <button>提交</button>
  12. </form>
  13. </body>
  14. </html>

4.5 handler 方法

  • 示例:
  1. package com.github.fairy.era.mvc.handler;
  2. import com.github.fairy.era.mvc.entity.Student;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.PostMapping;
  7. /**
  8. * @author 许大仙
  9. * @version 1.0
  10. * @since 2021-11-16 13:39
  11. */
  12. @Controller
  13. public class StudentHandler {
  14. private final Logger logger = LoggerFactory.getLogger(this.getClass());
  15. @PostMapping("/save/student")
  16. public String saveStudent(Student student) {
  17. logger.info("StudentHandler类的saveStudent方法的请求参数是:{}", student);
  18. return "target";
  19. }
  20. }
  • 在目前代码的基础上,我们没有提供自定义的类型转换器,所以在处理请求的时候会看到如下的错误日志:

[13:42:31.607] [DEBUG] [http-nio-8080-exec-6] [org.springframework.web.servlet.DispatcherServlet] [POST “/ajax/save/student”, parameters={masked}]
[13:42:31.640] [WARN ] [http-nio-8080-exec-6] [org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver] [Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errorsField error in object ‘student’ on field ‘address’: rejected value [aaa,bbb,ccc]; codes [typeMismatch.student.address,typeMismatch.address,typeMismatch.com.github.fairy.era.mvc.entity.Address,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [student.address,address]; arguments []; default message [address]]; default message [Failed to convert property value of type ‘java.lang.String’ to required type ‘com.github.fairy.era.mvc.entity.Address’ for property ‘address’; nested exception is java.lang.IllegalStateException: Cannot convert value of type ‘java.lang.String’ to required type ‘com.github.fairy.era.mvc.entity.Address’ for property ‘address’: no matching editors or conversion strategy found]]]
[13:42:31.640] [DEBUG] [http-nio-8080-exec-6] [org.springframework.web.servlet.DispatcherServlet] [Completed 400 BAD_REQUEST]

  • 当然,页面会抛出 400 错误。

SpringMVC类型转换失败后的默认结果.png

4.6 创建自定义类型转换器

  • 实现接口:org.springframework.core.convert.converter.Converter<S,T>
  • 其中,S 是源类型(本例中是 String 类型),T 是目标类型(本例中是 Address 类型)。

  • 示例:

  1. package com.github.fairy.era.mvc.converter;
  2. import com.github.fairy.era.mvc.entity.Address;
  3. import org.springframework.core.convert.converter.Converter;
  4. /**
  5. * @author 许大仙
  6. * @version 1.0
  7. * @since 2021-11-16 13:53
  8. */
  9. public class String2AddressConverter implements Converter<String, Address> {
  10. @Override
  11. public Address convert(String source) {
  12. // 1.按照约定的规则拆分源字符串
  13. String[] split = source.split(",");
  14. // 2.根据拆分结果创建 Address 对象
  15. Address address = new Address();
  16. address.setProvince(split[0]);
  17. address.setCity(split[1]);
  18. address.setStreet(split[2]);
  19. // 3.返回转换得到的对象
  20. return address;
  21. }
  22. }

4.7 在 SpringMVC 中注册

  • springmvc.xml
  1. <mvc:annotation-driven conversion-service="formattingConversionService"/>
  2. <!-- 在 FormattingConversionServiceFactoryBean 中注册自定义类型转换器 -->
  3. <bean id="formattingConversionService"
  4. class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
  5. <!-- 在 converters 属性中指定自定义类型转换器 -->
  6. <property name="converters">
  7. <set>
  8. <bean class="com.github.fairy.era.mvc.converter.String2AddressConverter"></bean>
  9. </set>
  10. </property>
  11. </bean>
  • 完整的 springmvc.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns="http://www.springframework.org/schema/beans"
  5. 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">
  6. <!-- 自动扫描包 -->
  7. <context:component-scan base-package="com.github.fairy.era.mvc.handler" use-default-filters="false">
  8. <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  9. </context:component-scan>
  10. <!-- 配置视图解析器 -->
  11. <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
  12. <property name="order" value="1"/>
  13. <property name="characterEncoding" value="UTF-8"/>
  14. <property name="templateEngine">
  15. <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
  16. <property name="templateResolver">
  17. <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
  18. <!-- 物理视图:视图前缀+逻辑视图+视图后缀 -->
  19. <!-- 视图前缀 -->
  20. <property name="prefix" value="/WEB-INF/templates/"/>
  21. <!-- 视图后缀 -->
  22. <property name="suffix" value=".html"/>
  23. <property name="templateMode" value="HTML5"/>
  24. <property name="characterEncoding" value="UTF-8"/>
  25. </bean>
  26. </property>
  27. </bean>
  28. </property>
  29. </bean>
  30. <mvc:annotation-driven conversion-service="formattingConversionService"/>
  31. <!-- 在 FormattingConversionServiceFactoryBean 中注册自定义类型转换器 -->
  32. <bean id="formattingConversionService"
  33. class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
  34. <!-- 在 converters 属性中指定自定义类型转换器 -->
  35. <property name="converters">
  36. <set>
  37. <bean class="com.github.fairy.era.mvc.converter.String2AddressConverter"></bean>
  38. </set>
  39. </property>
  40. </bean>
  41. <mvc:default-servlet-handler/>
  42. <mvc:view-controller path="/" view-name="portal"/>
  43. </beans>