【问题标题】:send json to server spring 3.x将 json 发送到服务器 spring 3.x
【发布时间】:2011-07-11 12:45:12
【问题描述】:

我想使用 Spring 3.x 将 json 发送到服务器,我使用注释 @RequestBody,但我的控制器没有调用。

请给我一个完整的例子,如果有的话,我正在尝试在 http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/ 但它不起作用。这是一个javascript代码

function sendAjax() {
var person = new Object();
person.firstname = "Firsname";
person.lastname = "Lastname";

jQuery.ajax({ 
    url: "person", 
    type: 'POST', 
    dataType: 'json', 
    data: person, 
    contentType: 'application/json', 
    success: function(data) { 
        alert(data.firstname + " " + data.lastname);
    } 
});}

我的控制器是

@Controller public class AjaxController {

@RequestMapping(value="person", method = RequestMethod.POST)
public @ResponseBody Person getRequest(@RequestBody Person person) {        
    System.out.println(person.getFirstname() + " " + person.getLastname());
    return new Person("Return", "Body");
}}

我的 xml 文件

<mvc:annotation-driven />               
<context:component-scan base-package="com.synisys.spring.test.controllers" />
<context:annotation-config/> 

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

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

<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>

【问题讨论】:

  • 会发生什么?你有错误吗?有日志输出吗?
  • 什么也没发生。我的控制器只是没有调用。如果我在我的控制器中删除@RequestBody,它会起作用

标签: jquery json spring spring-mvc


【解决方案1】:

请确保你有

 <context:annotation-config/> 

还有

<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>

在你的 spring xml conf 文件中。

【讨论】:

【解决方案2】:

在你的 ajax 调用中添加

var dat = JSON.stringify({
    "firstname " : firstname ,
    "lastname ": lastname 
});

jQuery.ajax({ 
    url: "person", 
    type: 'POST', 
    dataType: 'json', 
    data: person, 
    contentType: 'application/json', 
    success: function(data) { 
        alert(data.firstname + " " + data.lastname);
    } 
});

并确保添加相关依赖项(如果您使用的是 maven Spring mvc)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 2011-05-06
    相关资源
    最近更新 更多