问题导读:
1. Converter 转换器
2. Formatter 格式化
解决方案:
Converter 转换器
代码托管:https://github.com/LiPenglin/MySpringMVC/tree/master/SpringMVCDemo3
流程
- 创建属于自己的converter 类,这个converter 类需要实现 org.springframework.core.convert.converter.Converter 泛型接口,注意源类型和目标类型
- 在Spring MVC 配置文件中配置好 ConversionServiceFactoryBean
实现
主要代码
package Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
* 创建Converter
* 1. 实现 org.springframework.core.convert.converter.Converter 接口
* 2. Converter<S, T> S -> 源类型 T -> 目标类型
*/
import org.springframework.core.convert.converter.Converter;
public class StringToDateConverter implements Converter<String, Date>{
// 日期格式
private String datePattern;
public StringToDateConverter(String datePattern) {
this.datePattern = datePattern;
}
@Override
public Date convert(String s) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern);
// 如果日期不合格则需要抛出异常,不能正常计算,所以要禁止SimpleDateFormat的自动计算功能
dateFormat.setLenient(false);
return dateFormat.parse(s);
} catch (ParseException e) {
throw new IllegalArgumentException("非法参数异常,时期格式错误!");
}
}
}
<?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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 扫描包 -->
<context:component-scan base-package="controller" />
<!-- 视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!--
配置 conversionService bean
1. bean 名称:org.springframework.context.support.ConversionServiceFactoryBean
2. bean 必备属性:converters 列出所有定制的Converter
-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="Converter.StringToDateConverter">
<constructor-arg type="java.lang.String" value="yyyy/MM/dd" />
</bean>
</list>
</property>
</bean>
<mvc:annotation-driven conversion-service="conversionService"/>
</beans>
测试
正确格式
错误格式
Formater 格式化
- 实现类似converter,详细参考《Spring MVC 学习指南》第六章
- Converter 可以将随便一种类型转换成另一种类型,可以应用在web层也可以在其他层
- Formatter 更适用于web 层,只能将String 转成 Java 类型