有时候我们会碰到这么一个问题,有一个实体类,里面有一个Date类型的数据,jsp页面传递的时间参数是String的,这就导致无法对应,springmvc无法帮我们自动封装参数到实体类中了,这里我解决的方法有两种:
1.是自定义一个转换器,实现Converter<S,T>接口,S:代表要进行转换的参数的类型,T:代表转换后的类型
2.利用@DateTimeFormat注解
1 简单测试代码如下:DateConverter类中conver()方法将字符串转化为自定义的时间类型,当前台页面发送请求中有参数为string类型,而在后台接收时用Date类型直接接收,因为转换器会帮我们转化
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateConverter implements Converter<String, Date> { private static final SimpleDateFormat dateF=new SimpleDateFormat("yyyy-MM-dd hh:mm"); /** * Converter为一个接口。该接口有很多实现类 * 比如 StringToBooleanConverter string自动转化为Boolean * */ @Override public Date convert(String s) { Date date=null; if(CheckUtil.isNotEmpty(s)){ try { date=dateF.parse(s); } catch (ParseException e) { new Throwable("字符串转换时间异常"); } } return date; } }
该转换器如果要实现,还需要将器注册到mvc注解驱动中,让注解驱动的conversion-service使用我们自定义的
<bean id="conversionServiceFactoryBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.paic.utils.converter.DateConverter"></bean><!--将自定义的时间转换注入进去--> </list> </property> </bean> <!--开启springmvc注解的支持--> <mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/>
由于set对象时是加到了list中,所以并不影响其他的之前已经存在的类型转换实现类
2 简单测试代码如下,实体类上加@DateTimeFormat
public class Product { private String id; // 主键 private String productNum; // 编号 唯一 private String productName; // 名称 private String cityName; // 出发城市 @DateTimeFormat(pattern="yyyy-MM-dd hh:ss") private Date departureTime; // 出发时间 private String departureTimeStr; private double productPrice; // 产品价格 private String productDesc; // 产品描述 private Integer productStatus; // 状态 0 关闭 1 开启 private String productStatusStr;
两中方式的区别在于第一种在项目中适用,第二种在当前实体类中适用