springmvc中实现可以自动把请求的String转换为Data日期对象
前言
java学习小计,自定义类型转换器,是在ssm项目中遇到的问题的解决方案
第一步:控制器添加如下测试方法
@Controller
@RequestMapping("/company")
public class CompanyController {
@RequestMapping("/save")
public String save(Date data){
System.out.println("转换的日期:"+ data);
return "success";
}
}
第二步:访问测试
string类型的日期无法自动转换成日期类型
第三步:编写一个转换器类
日期类型转换器的定义步骤:
1. 自定义一个类实现Converter接口
2. 实现Converter接口
3. 创建日期类型转换器的对象
4. 把日期类型转换器的对象交给转换器的工厂
5. 类型转换器的工厂交给注解驱动去启动
import org.springframework.core.convert.converter.Converter;
@Component
public class StringToDateConverter implements Converter<String,Date> {
@Override
public Date convert(String source) { //source=1999-12-12字符串
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = simpleDateFormat.parse(source);
return date;
} catch (ParseException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
第四步:在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 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--1. 配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--2.包扫描-->
<context:component-scan base-package="cn.itcast.web"/>
<!--3. 开启注解驱动-->
<!--<mvc:annotation-driven/>-->
<!--==================================注册日期类型转换器=============================================-->
<!--4. 把日期类型转换器的对象交给转换器的工厂-->
<bean id="conversionServiceFactory" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<ref bean="stringToDateConverter"/>
</set>
</property>
</bean>
<!--5. 类型转换器的工厂交给注解驱动去启动,记得删除上面的注解驱动,一句即可-->
<mvc:annotation-driven conversion-service="conversionServiceFactory"/>
</beans>