在我们实际编码中,通常都会遇到传数据时,类型不匹配的问题,现在我们就来学习如何实现日期转换问题。
1、创建商品录入页面:
2、创建商品实体类:
public class Goods {
private String name; //商品名称
private String type; //商品类型
private double price; //商品价格
private Date date; //商品上架时间
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {
return "Goods [name=" + name + ", type=" + type + ", price=" + price + ", date=" + date + "]";
}
}
3、创建类型转换类:
public class StringToDeteConverter implements Converter<String, Date>{
@Override
public Date convert(String source) {
Date date =null;
SimpleDateFormat format=null;
try {
//设置编码格式
format=new SimpleDateFormat("yyyy-mm-dd");
//转换格式
date = format.parse(source);
} catch (Exception e) {
format=new SimpleDateFormat("yyyy/mm/dd");
try {
date = format.parse(source);
} catch (ParseException e1) {
System.out.println("日期转化失败");
e1.printStackTrace();
}
}
return date;
}
}
4、添加环境配置
<!-- 配置自定义类型转换服务 -->
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<!-- 注册所以自定义型转换 -->
<property name="converters">
<list>
<!-- 这里写类型转换类 -->
<bean class="com.zh.converter.StringToDeteConverter"/>
</list>
</property>
</bean>
<!-- conversionService为上面自定义服务的ID -->
<mvc:annotation-driven conversion-service="conversionService"/>
开启自动扫描页面控制器
<context:component-scan base-package="com.zh.controller" />
5、创建GoodsController类
@Controller // 指明页面控制器
public class GoodsController { // 请求映射页面控制器处理方法
@RequestMapping("goods")
public String checkIn(Goods goods) { //商品录入方法
return "GoodsSuccess";
}
}
这里把网页传入的多条数据封装成了一个对象,作为自定位方法的参数,框架会去自动检测里面的数据类型是否一致,如果不一致,就会通过配置文件自动转化!
6、创建跳转页面
接下来我不说了,你们也应该懂了!
。。。。