自定义Date参数绑定器
springmvc中对年月日默认提供绑定. 但对时分秒没有提供绑定
解决: 自定义参数绑定器. 实现日期的全部绑定
代码实现:
自定义参数绑定器实现Conver(S , T), S表示源类型. T表示自定义类型. S也就是页面请求参数类型. 即String
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
public class CustomDate implements Converter<String, Date>{
public Date convert(String source) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
try {
return dateFormat.parse(source);
} catch (ParseException e) {
e.printStackTrace();
// 如果转换失败返回null
return null;
}
}
}
在springmvc上配置参数绑定器
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- springmvc的处理器映射器和适配器的配置 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 使用组件扫描. 将@controller注解的类扫描出来在容器中进行注册 -->
<context:component-scan base-package="com.itcast.ssm.controller"></context:component-scan>
<!-- 自定义转换器 -->
<bean id="" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.itcast.ssm.converters.CustomDate"/>
</list>
</property>
</bean>
<!-- 配置视图解析器. 解析jsp视图 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 指定视图的前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!-- 指定视图的后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>