对于一些URL中传过来的参数,而接口无法按我们想要的格式来进行接收,这些可以使用如下的方法。
如URL带有时间的参数,以字符类型传参,而接口中想使用Date类型接收,这时就需要做一些处理。
@RequestMapping("date") @ResponseBody public String date(Date date) { return date.toString(); }
浏览器输入:http://localhost:8080/date?date=2018-12-21 22:13:22
一、使用PropertyEditor
@InitBinder("date") public void initDate(WebDataBinder webDataBinder) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); CustomDateEditor customDateEditor = new CustomDateEditor(sdf, true); webDataBinder.registerCustomEditor(Date.class, customDateEditor); }
返回:Fri Dec 21 22:13:22 CST 2018
注:SpringMVC中提供了很多的PropertyEditor的实现类,CustomDateEditor就是其中之一,它提供了时间格式的数据转换方法。将其注册到binder中,可实现时间参数的接收转换。
二、使用Formatter
InitBinder只能在当前的Controller中使用,如果多个Controller需要使用同样的时间转换,就需要提供能全局使用的方法。
实现Formatter接口
public class MyDateFormatter implements Formatter<Date> { public Date parse(String text, Locale locale) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return sdf.parse(text); } public String print(Date object, Locale locale) { return null; } }
spring-mvc.xml中增加配置
<bean id="myDateFormatter" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="formatters"> <set> <bean class="param.MyDateFormatter"/> </set> </property> </bean>
<mvc:annotation-driven conversion-service="myDateFormatter" />返回:Fri Dec 21 22:13:22 CST 2018
注:anotation-driven中需增加conversion-service配置,否则将不生效
三、使用Converter
熟悉Converter接口
public class MyDateConverter implements Converter<String, Date> { public Date convert(String source) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { return sdf.parse(source); } catch (ParseException e) { e.printStackTrace(); } return null; } }spring-mvc.xml中增加配置
<bean id="myDateConverter" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="param.MyDateConverter"/> </set> </property> </bean>
<mvc:annotation-driven conversion-service="myDateConverter" />
返回:Fri Dec 21 22:13:22 CST 2018