数据绑定

SpringMVC 将“把请求参数注入到 POJO 对象”这个操作称为“数据绑定”。

数据类型的转换和格式化就发生在数据绑定的过程中。 类型转换和格式化是密不可分的两个过程,很多带格式的数据必须明确指定格式之后才可以进行类型转换。最典型的就是日期类型。

SpringMVC 内置的类型转换器

1、配置 MVC 注解驱动

1
<mvc:annotation-driven/>

2、在需要进行转换的字段上标记特定的注解

1
2
3
4
5
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birthday;

@NumberFormat(pattern="#,###,###.#")
private double salary;

转换失败后处理

1、BindingResult

SpringMVC 在捕获到类型转换失败错误时会将相关信息封装到BindingResult对象传入到目标 handler 方法中。

1
2
3
4
/**
* Return if there were any errors.
*/
boolean hasErrors();

在 handler 可以通过hasErrors()方法判断是否有错误。如果有则跳转到指定的页面。当然如果有需要也可以获取其他相关信息。

1
2
3
4
5
6
7
8
9
10
@RequestMapping("/saveEmp")
public String saveEmp(Employee employee, BindingResult result) {

if(result.hasErrors()) {

return "add";
}

return "success";
}

注意:这里传入 Employee 和 BindingResult 这两个参数时中间不能有别的入参声明。

2、页面显示

[1]要借助 SpringMVC 的 form:form 标签

[2]在 form:form 标签中要明确指定 modelAttribute 属性。

[3]使用 form:errors 标签,通过 path 属性指定要显示错误消息的属性名

1
<form:input path="birthday"/><form:errors path="birthday"/>

自定义类型转换器

1、Converter<S,T>接口

自定义类型转换器要实现Converter<S,T>这个接口

2、配置 FormattingConversionServiceFactoryBean

FormattingConversionServiceFactoryBeanconverters属性中配置自定义类型转换器的全类名

1
2
3
4
5
6
7
<bean id="conversionServiceFactoryBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.atguigu.mvc.converters.EmpConverter"/>
</set>
</property>
</bean>

3、配置 mvc:annotation-driven

1
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/>