【问题标题】:Getting Spring MVC to work with JodaModule让 Spring MVC 与 JodaModule 一起工作
【发布时间】:2016-01-11 17:31:31
【问题描述】:

这有点令人沮丧...我以前的项目中有这个工作,但在调试几个小时后无法让它在我的新项目中工作。

假设我有一个简单的 Rest 控制器,它返回 Joda 的 LocalDate:-

@RestController
@RequestMapping(value = "/api")
public final class ApiController {
    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<LocalDate> main() {
        return new ResponseEntity<LocalDate>(LocalDate.now(), HttpStatus.OK);
    }
}

默认情况下,当我调用http://app/api 时,我会得到[2015,10,13]。我真正想要的是2015-10-13

为了在我之前的项目中解决这个问题,我在spring-servlet.xml 中使用了这个配置:-

<?xml version="1.0" encoding="UTF-8"?>
<beans ...>

    <context:component-scan base-package="test.controller"/>

    <mvc:annotation-driven/>

    <mvc:resources location="/resources/" mapping="/resources/**"/>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="objectMapper"
          class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
          p:indentOutput="true"
          p:simpleDateFormat="yyyy-MM-dd'T'HH:mm:ss.SSSZ">
    </bean>

    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"
          p:targetObject-ref="objectMapper"
          p:targetMethod="registerModule">
        <property name="arguments">
            <list>
                <bean class="com.fasterxml.jackson.datatype.joda.JodaModule"/>
            </list>
        </property>
    </bean>

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper" ref="objectMapper"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
</beans>

但是,当我在我的新项目中做同样的事情时,我又得到了[2015,10,13] 而不是2015-10-13

我确实升级了一些依赖项,并且我还确保没有额外的 ObjectMapper 被加载。

这是我当前的依赖树...我删除了所有我不需要的东西:-

如何配置 Spring MVC 以在 JSON 中返回正确的日期格式?

非常感谢。

【问题讨论】:

    标签: java spring spring-mvc jackson jodatime


    【解决方案1】:

    您两次声明了&lt;mvc:annotation-driven&gt;。尝试删除第一个声明(空的,默认配置)。您在第二个 &lt;mvc:annotation-driven&gt; 中配置的消息转换器可能会被第一个声明覆盖(使用默认消息转换器)。

    【讨论】:

    • 我的天哪....你说的完全正确,不知何故我什至没有注意到这一点。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2013-11-11
    • 2011-04-17
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多