SpringMVC 四种方法解决表单到后台的日期类型转换

xiaoxiao2021-02-28  53

         基本上所有的注册页面都有出生日期一栏,所对应的pojo都应该有一个java.util.Date类型的,名为birth的属性.  那么问题来了, 请求只能传递字符串, 如果不作处理, 会出现"HTTP Status 400 – Bad Request"的错误, 并且报错信息也只有令人匪夷所思的一行英文, 后台更是一点反应都没.     有问题出现当然就有解决的办法, 并且有时候还不止一种, 下面介绍四种常用的解决方案. 1 .使用Spring的@DateTimeFormat注解         使用方法: 在对应的属性上或者其set方法上加上@DateTimeFormat注解, 这个注解有一个pattern属性, 可以指定要日期的格式. 就像这样: @DateTimeFormat(pattern = "yyyy-MM-dd") private Date birth;

还需要在配置文件中添加"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注入,使得日期格式的灵活修改.

转载请注明原文地址: https://www.6miu.com/read-2621547.html

最新回复(0)