Springmvc框架-json数据格式传递过程中-将时间戳转化成标准的日期格式-@JSONField - dongyaotou - 博客园

 在上一个小demo中,我们能够看出,其实返回的日期格式也是不对的,现在返回的是一个时间戳,并不是一个标准的日期格式。

解决办法:

第一种:在要转化的实体类中添加@JSONField注解

 

第二种:配置fastjson的消息转换器,来处理日期格式的问题

springmvc-servlet.xml

复制代码; "复制代码")

1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
4 xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
5 xsi:schemaLocation="
6 http://www.springframework.org/schema/beans
7 http://www.springframework.org/schema/beans/spring-beans.xsd
8 http://www.springframework.org/schema/context
9 http://www.springframework.org/schema/context/spring-context.xsd
10 http://www.springframework.org/schema/mvc
11 http://www.springframework.org/schema/mvc/spring-mvc.xsd">
12
13 <context:component-scan base-package="cn.smbms.controller" />
14 <mvc:annotation-driven>
15 <!-- 添加消息转换器 解决json数据传递过程中的乱码问题 -->
16 <mvc:message-converters>
17 <bean class="org.springframework.http.converter.StringHttpMessageConverter">
18 <!-- 设置相应的属性 -->
19 <property name="supportedMediaTypes">
20 <list>
21 <value>application/json;charset=UTF-8</value>
22 </list>
23 </property>
24 </bean>
25 <!-- 日期格式的转化 -->
26 <bean 27 class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
28 <property name="supportedMediaTypes">
29 <list>
30 <value>text/html;charset=UTF-8</value>
31 <value>application/json</value>
32 </list>
33 </property>
34 <property name="features">
35 <list>
36 <!--WriteDateUseDateFormat这是fastjson默认的日期转换格式 -->
37 <value>WriteDateUseDateFormat</value>
38 </list>
39 </property>
40 </bean>
41 </mvc:message-converters>
42 </mvc:annotation-driven>
43
44 <mvc:resources mapping="/statics/**" location="/statics/" />
45 <!-- 完成视图的对应 -->
46 <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
47 <bean 48 class="org.springframework.web.servlet.view.InternalResourceViewResolver">
49 <property name="prefix" value="/WEB-INF/jsp/" />
50 <property name="suffix" value=".jsp" />
51 </bean>
52
53 <!-- 全局异常处理 -->
54 <bean 55 class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
56 <property name="exceptionMappings">
57 <props>
58 <prop key="java.lang.RuntimeException">error</prop>
59 </props>
60 </property>
61 </bean>
62
63 <!--配置MultipartResolver,用于文件上传 -->
64 <bean id="multipartResolver"
65 class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
66 <property name="maxUploadSize" value="5000000"></property>
67 <property name="defaultEncoding" value="UTF-8"></property>
68 </bean>
69
70 </beans>

复制代码; "复制代码")

 修改UserController.java 这里就不再需要将返回的实体对象转换成json了

 运行结果:

 观察:现在返回的时间给精确到秒了

原因:

 解决办法:

使用@JSONField控制某个要显示的字段就可以了

 


Original url: Access
Created at: 2020-08-06 19:45:33
Category: default
Tags: none

请先后发表评论
  • 最新评论
  • 总共0条评论