年三十居然在家写随笔,泪奔啊。还是投身在代码中吧......
在数据绑定上,SpringMVC提供了到各种基本类型的转换,由前端到后台时,SpringMVC将字符串参数自动转换为各种基本类型。而对于其他,则需要自己编写转换器进行转换。本随笔以转换时间类型为例。
转换器都必须实现Converter接口,该接口原型如下:
public interface Converter<S, T> { T convert(S source); }
编写DateConverter,该转换器可以自定义转换格式,默认为年-月-日:
public class DateConverter implements Converter<String, Date> { private String pattern = "yyyy-MM-dd"; public void setPattern(String pattern) { this.pattern = pattern; } @Override public Date convert(String source) { if (source == null || source.trim().isEmpty()) return null; DateFormat format = new SimpleDateFormat(pattern); Date date = null; try { date = format.parse(source.trim()); } catch (ParseException e) { } return date; } }
接下来是注册该转换器:
<mvc:annotation-driven conversion-service="conversionService" /> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="cn.powerfully.demo.web.controller.DateConverter" /> </set> </property> </bean>
完成!
原文:http://www.cnblogs.com/loading4/p/6354006.html