无法从带注释的控制器获取自动格式化的json数据

时间:2011-02-07 14:38:22

标签: jquery json spring-mvc annotations jackson

根据我的理解,如果您使用mvc:annotation-driven标记,那么您可以传回JSON格式的对象,前提是相关的jackson jar文件存在于类路径中。情况就是这样。

但是,我从服务器收到406(不可接受)的响应。

这是带注释的控制器的相关部分:

@RequestMapping(value = "/{groupEventUID}/{attendeeId}/update2.htm", method = RequestMethod.POST)
public
@ResponseBody
DateResponse submitDate2(@PathVariable String groupEventUID, @PathVariable int attendeeId, ModelMap model) {
    return new DateResponse();
}

这是客户端页面上的jquery代码:

    <script type="text/JavaScript"> 
        $(document).ready(function(){
            $(".dayblock").click(function(){
                $(event.target).css('background-color','green');

                $.ajax({
                    url: "update2.htm",
                    type: "POST",
                    dataType: "json",
                    success: function(data){
                        alert("Data Loaded: " + data);
                    }
                }); 
            });
        });
    </script> 

我尝试放置在类路径中的杰克逊罐子是:

jackson-core-asl-1.7.2.jar和jackson-mapper-asl-1.7.2.jar

我也试过

杰克逊 - 全1.7.2.jar

仍然是可怕的406 ..

是否需要显式注释DateResponse对象以将其转换为JSON?我原以为使用现有的字段名称将是默认行为。

我认为最令人沮丧的是我看不到任何后端异常,所以我正在尝试试错。

编辑:以下是http标头

Request URL:http://localhost:8080/7uid/5/update2.htm
Request Method:POST
Status Code:406 Not Acceptable

Request Headers

Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Connection:keep-alive
Content-Length:0
Cookie:JSESSIONID=C8B515F9BE0773BF7916E3FA7F17EE30
Host:localhost:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/7uid/5/showAttendeeCalendar.htm
User-Agent:Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.597.84 Safari/534.13
accept:application/json, text/javascript, */*; q=0.01
x-requested-with:XMLHttpRequest

Response Headers

Cache-Control:no-cache
no-store
Content-Length:1070
Content-Type:text/html;charset=utf-8
Date:Mon, 07 Feb 2011 16:31:03 GMT
Expires:Thu, 01 Jan 1970 00:00:00 GMT
Pragma:no-cache
Server:Apache-Coyote/1.1

这是dispatcher-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:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd" >


    <context:component-scan base-package="com.crowdbot.nightout.web"/>
    <context:component-scan base-package="com.crowdbot.nightout.dao"/>


    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />

    <!--
    Most controllers will use the ControllerClassNameHandlerMapping above, but
    for the index controller we are using ParameterizableViewController, so we must
    define an explicit mapping for it.
    -->
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index.htm">indexController</prop>
            </props>
        </property>
    </bean>


    <!--
    The index controller.
    -->
    <bean name="indexController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="index" />


    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />


    <bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="loadTimeWeaver">
            <bean class="org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver"/>
        </property>
    </bean>


    <bean id="myTxManager"
     class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="emf"/>
    </bean>

    <tx:annotation-driven transaction-manager="myTxManager" />


    <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jacksonMessageConverter"/>
            </list>
        </property>
    </bean>

    <mvc:annotation-driven/>

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


</beans>

EDIT2:这是catalina.out

07-Feb-2011 17:05:46 org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /opt/java/jdk1.6.0_21/jre/lib/amd64/server:/opt/java/jdk1.6.0_21/jre/lib/amd64:/opt/java/jdk1.6.0_21/jre/../lib/$
07-Feb-2011 17:05:46 org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
07-Feb-2011 17:05:46 org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 786 ms
07-Feb-2011 17:05:46 org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
07-Feb-2011 17:05:46 org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.29
07-Feb-2011 17:05:46 org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor host-manager.xml
07-Feb-2011 17:05:46 org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor ROOT.xml
07-Feb-2011 17:05:47 org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
07-Feb-2011 17:05:47 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Mon Feb 07 17:05:47 GMT 2011]; root of context hierarchy
07-Feb-2011 17:05:47 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
07-Feb-2011 17:05:47 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3cc70b0d: defining beans []; root of factory hierarchy
07-Feb-2011 17:05:47 org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 329 ms
07-Feb-2011 17:05:47 org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'dispatcher': initialization started
07-Feb-2011 17:05:47 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Mon Feb 07 17:05:47 GMT 2011]; parent: Root WebApplicationContext
07-Feb-2011 17:05:47 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/dispatcher-servlet.xml]
07-Feb-2011 17:05:48 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@228b677f: defining beans [mainController,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annot$
07-Feb-2011 17:05:48 org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean createNativeEntityManagerFactory
INFO: Building JPA container EntityManagerFactory for persistence unit 'NightOutPU'
07-Feb-2011 17:05:49 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/main] onto handler [com.crowdbot.nightout.web.MainController@41a7c484]
07-Feb-2011 17:05:49 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/main/*] onto handler [com.crowdbot.nightout.web.MainController@41a7c484]
07-Feb-2011 17:05:49 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/index.htm] onto handler [org.springframework.web.servlet.mvc.ParameterizableViewController@4d3af084]
07-Feb-2011 17:05:49 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/addEditGroupEvent.htm] onto handler [com.crowdbot.nightout.web.MainController@41a7c484]
07-Feb-2011 17:05:49 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/groupEventSuccess.htm] onto handler [com.crowdbot.nightout.web.MainController@41a7c484]
07-Feb-2011 17:05:49 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/{groupEventUID}/addEditAttendee.htm] onto handler [com.crowdbot.nightout.web.MainController@41a7c484]
07-Feb-2011 17:05:49 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/{groupEventUID}/showAttendees.htm] onto handler [com.crowdbot.nightout.web.MainController@41a7c484]
07-Feb-2011 17:05:49 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/{groupEventUID}/{attendeeId}/showAttendeeCalendar.htm] onto handler [com.crowdbot.nightout.web.MainController@41a7c484]
07-Feb-2011 17:05:49 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/{groupEventUID}/{attendeeId}/update.htm] onto handler [com.crowdbot.nightout.web.MainController@41a7c484]
07-Feb-2011 17:05:49 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/{groupEventUID}/{attendeeId}/update2.htm] onto handler [com.crowdbot.nightout.web.MainController@41a7c484]
07-Feb-2011 17:05:49 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/addEditGroupEvent.htm] onto handler [com.crowdbot.nightout.web.MainController@41a7c484]
07-Feb-2011 17:05:49 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/groupEventSuccess.htm] onto handler [com.crowdbot.nightout.web.MainController@41a7c484]
07-Feb-2011 17:05:49 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/{groupEventUID}/addEditAttendee.htm] onto handler [com.crowdbot.nightout.web.MainController@41a7c484]
07-Feb-2011 17:05:49 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/{groupEventUID}/showAttendees.htm] onto handler [com.crowdbot.nightout.web.MainController@41a7c484]
07-Feb-2011 17:05:49 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/{groupEventUID}/{attendeeId}/showAttendeeCalendar.htm] onto handler [com.crowdbot.nightout.web.MainController@41a7c484]
07-Feb-2011 17:05:49 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/{groupEventUID}/{attendeeId}/update.htm] onto handler [com.crowdbot.nightout.web.MainController@41a7c484]
07-Feb-2011 17:05:49 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/{groupEventUID}/{attendeeId}/update2.htm] onto handler [com.crowdbot.nightout.web.MainController@41a7c484]
07-Feb-2011 17:05:49 org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'dispatcher': initialization completed in 1909 ms
07-Feb-2011 17:05:49 org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor manager.xml
07-Feb-2011 17:05:49 org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory docs
07-Feb-2011 17:05:49 org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory examples
07-Feb-2011 17:05:49 org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080

这是同一时期的localhost日志:

07-Feb-2011 17:05:47 org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
07-Feb-2011 17:05:47 org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
07-Feb-2011 17:05:49 org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextInitialized()
07-Feb-2011 17:05:49 org.apache.catalina.core.ApplicationContext log
INFO: SessionListener: contextInitialized()

2 个答案:

答案 0 :(得分:2)

好的,它已修复。

问题在于我已经注册了DefaultAnnotationHadlerMapping和AnnotationMethodHandlerAdapter。我怀疑这些与标签设置的bean冲突。我想当你尝试将一堆不同的教程混合在一起时会发生这种情况!

评论它们可以解决问题。

<!--<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> -->
<!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> -->

感谢大家的帮助!

答案 1 :(得分:1)

请确保您在Spring配置xml中有参考。

<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
  <list>
    <ref bean="jacksonMessageConverter"/>
  </list>
</property>
</bean> 

andcouse:

<mvc:annotation-driven>