本例使用场景:
后台代码返回日期数据要在前台页面中显示,且要求格式:2019-03-04 15:36:03
在没有配置前返回前台数据是:1551684963000
配置后:2019-03-04 15:36:03
本例环境:
eclipse MARS2 + 基于maven的web项目+jdk7 + spring4.x
1.继承ObjectMapper,写个自定义类CustomObjectMapper
public class CustomObjectMapper extends ObjectMapper {
private static final long serialVersionUID = -5422983207643006489L;
public CustomObjectMapper() {
//禁止使用时间戳
this.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//设置为中国时区
this.setTimeZone(TimeZone.getTimeZone("GMT+8"));
//设置日期格式
this.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
}
2.在springMVC配置文件中配置如下即可
<mvc:annotation-driven
content-negotiation-manager="contentNegotiationManager">
<mvc:message-converters register-defaults="true">
<!-- 将StringHttpMessageConverter的默认编码设为UTF-8 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" />
</bean>
<!-- 将Jackson2HttpMessageConverter的默认格式化输出为false -->
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
<property name="prettyPrint" value="false" />
<property name="objectMapper">
<bean class="com.zbz.config.CustomObjectMapper"></bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- REST中根据URL后缀自动判定Content-Type及相应的View -->
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="mediaTypes">
<map>
<entry key="xml" value="application/xml" />
<entry key="json" value="application/json" />
</map>
</property>
<property name="ignoreAcceptHeader" value="true" />
<property name="favorPathExtension" value="true" />
</bean>
以上,TKS.