在上一個小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控制某個要顯示的字段就可以了