首先定义一个接收Date类型的handler,代码以下:ajax
@GetMapping(value = "/hour", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public String getHourAverage(@RequestParam(value = "startTime") Date startTime, @RequestParam(value = "endTime") Date endTime){ return "startTime:" + startTime + "endTime" + endTime; }
而后须要定义一个类型转换器,此类须要实现Converter<String, Date>接口,代码以下:spring
public class DateConvert implements Converter<String, Date> { private Logger LOGGER = LoggerFactory.getLogger(DateConvert.class); @Override public Date convert(String s) { try { return DateUtil.parse(s); }catch (Exception e){ LOGGER.error("Date convert exception, source :"+ s +",exception:", e); } return null; } }
最后须要将此转换器注入到FormattingConversionServiceFactoryBean中,Spring中的配置代码以下json
<mvc:annotation-driven conversion-service="customConversionService"/>浏览器
<bean id="customConversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.zjut.convert.DateConvert"></bean> </set> </property> </bean>
完成此配置后,便可在hanler中接收Date类型的参数。开启此服务,在浏览器中输入:mvc
http://localhost:8088/average/hour.ajax?startTime=2017-01-01%2012:12:12&&endTime=2017-09-09%2012:12:12
会获得如下输出:app
在使用SpringMVC实现返回json字符串的接口时候,当返回的数据类型由Date类型的时候,须要对这种类型作特殊的转换才能获得咱们想要的格式化的时间字符串,实现此功能只须要在Model类中的get方法作简单的处理便可,首先咱们须要添加jackson依赖,配置以下:ide
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-core-asl --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> </dependency>
添加依赖后,只须要在Date类型的字段的get方法中添加以下注解便可,以下:spa
@JsonFormat(pattern = DateUtil.DEFAULT_DATE_FORMAT) public Date getCreatedTime() { return createdTime; }
其中pattern参数为格式化参数。经过以上配置以后,访问接口后获得的数据以下所示,能够看到createTime格式为时间字符串:code