还需要在配置文件中添加"mvc:annotation-driven"这个标签, 否则不生效.
这种方法最简单,只需添加两处配置即可. 但只是局部生效, 若需要转换的属性比较多, 就造成了注解编写的冗余.
2.修改pojo属性的set方法, 手动在set方法中转换
使用方法: 还是以刚才的birth属性为例, 修改set方法的参数列表, 变为表示时间的字符串, 在方法内部进行处理转换.
public void setBirth(String birth) throws ParseException { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date rel_birth = format.parse(birth); this.birth = rel_birth; }都知道SpringMVC在对pojo设置属性值时会调用set方法, 那么我们就在set方法中使用java.text.SimpleDateFormat类对字符串进行转换. 比较巧妙的一种方法, 但同第一种方法一样, 局限性太大, 而且日期格式是硬编码, 不方便修改.
3 .使用WebDateBinder类进行转换使用方法: 上面两种方法都是修改pojo类, 这个方法我们在controller层做一些操作. 使用WebDateBinder类来转换(不了解这个类的戳这里).
@InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); //true:允许为空, false:不允许为空 }被@InitBinder注解修饰的方法会在SpringMVC为参数设置值之前调用, 并对参数做一些处理. 在这个方法内我们注册了一个自定义的类型为"CustomDateEditor"的"属性编辑器", 对日期格式字符串做了转化的操作.
这种办法适合只做web开发的程序员使用.
4.使用Spring的Convert接口,创建一个全局的日期类型转换器
使用方法: 自定义一个convert类并实现Convert<S,T>接口, 并实现这个接口的convert方法
public class DateConvert implements Converter<String, Date> { private String pattern; public void setPattern(String pattern) { this.pattern = pattern; } @Override public Date convert(String source) { SimpleDateFormat format = new SimpleDateFormat(pattern); Date d = null; try { d = format.parse(source); } catch (ParseException e) { e.printStackTrace(); } return d; } } <mvc:annotation-driven conversion-service="conversionService"/> <!-- 自定义的日期转换器--> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.ld.convert.DateConvert"> <!-- 自定义日期格式--> <property name="pattern" value="yyyy-MM-dd"/> </bean> </set> </property> </bean>这个是我最喜欢的方法, 因为它可以在全局范围内对日期进行转换, 做到了一次配置,永无后顾之忧的效果, 虽然修改的代码量相对于以上三种比较大,但有得就有失 . 并且我将pattern属性抽出,用Spring注入,使得日期格式的灵活修改.
