springMVC框架返回JSON到前端日期格式化

在Controller类中,需要返回JSON的方法上加上注释@ResponseBody,这是必须的。

然后spring-servlet.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="   
           http://www.springframework.org/schema/beans   
           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd   
           http://www.springframework.org/schema/context   
           http://www.springframework.org/schema/context/spring-context-4.0.xsd  
           http://www.springframework.org/schema/mvc   
           http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    
    <!-- 启动扫描所有的controller aokunsang-->
    <context:component-scan base-package="com.xxx"/>
    
    <!-- 定义注解驱动Controller方法处理适配器 ,注:该适配器必须声明在<mvc:annotation-driven />之前,否则不能正常处理参数类型的转换 -->  
    <bean  
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">  
        <property name="messageConverters">  
            <list>  
                <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />  
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" >
                    <property name="objectMapper">
                        <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                            <property name="dateFormat">
                                <bean class="java.text.SimpleDateFormat">
                                    <!-- 设置全局返回JSON到前端时日期格式化 -->
                                    <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss"/>
                                </bean>
                            </property>
                        </bean>
                    </property> 
                </bean>  
            </list>  
        </property>  
    </bean>  
   
    <!-- 会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter   
        两个bean,是spring MVC为@Controllers分发请求所必须的。 并提供了:数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson) -->  
    <mvc:annotation-driven />  
    
    <!-- 配置js,css等静态文件直接映射到对应的文件夹,不被DispatcherServlet处理 -->
    <mvc:resources location="/resources/**" mapping="/resources/**"/>
    
    <!-- jsp页面解析器,当Controller返回XXX字符串时,先通过拦截器,然后该类就会在/WEB-INF/views/目录下,查找XXX.jsp文件-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
</beans>

 

posted on 2017-07-28 14:38  梦幻朵颜  阅读(2624)  评论(0编辑  收藏  举报