Spring MVC& JQuery AJAX Post仅与@ResponseBody合作

时间:2016-08-03 12:12:51

标签: jquery spring-mvc

我在带有JQuery 1.8的HTML页面中有一个按钮。 我使用Spring MVC 4.1来处理请求。

      var test= "foo";
      $.ajax({
            type : "POST",
            async : false,
            url : "rest/ping",
            data : JSON.stringify(test),
            dataType : "json" ,
            contentType : "application/json",
            error : function(jqXHR, textStatus, errorThrown) {
                alert(errorThrown + " -- " + jqXHR.responseText);

            },
            success : function(data) {
                console.log("bar");
            }
        });

春天方面:

@Controller
@RequestMapping("/test")
public class DummyController {
@RequestMapping(value = "/rest/ping", method = RequestMethod.POST)
@ResponseBody
public void ping(@RequestBody String test) throws ServiceException{
    // nothing of concern
}
}

如果删除@ResponseBody,系统无法找到映射。如果我添加'(必需= false)'到请求体注释然后找到映射但是ajax调用失败,因为在调用映射的url之后,系统调用" test / rest / ping / rest / ping"。

如果您有JQuery和Spring MVC协同工作的文档,请将它们添加到此问题中。我无法找到描述这种奇怪行为的有效示例。 如果您有任何问题,请询问。 谢谢大家的时间。

2 个答案:

答案 0 :(得分:2)

由于您是通过JQuery进行XHR调用,因此需要

@ResponseBody。对于将返回特定数据格式(JSON,XML)的端点,以及不返回任何数据(void)的端点,都是如此。

否则,当未指定时,Spring需要返回一个ModelView对象,该对象将指向特定视图,并且可以使用模型哈希进行修饰。

在您的情况下,问题可能是JSON.stringify(test)期间您没有以下列形式提供有效的键值对: test=yourValue

有关Responsebody的更多信息,您可以查看this one

希望它有所帮助。

答案 1 :(得分:0)

您可以尝试进行更改吗

删除控制器的@RequestMapping(“/ test”)。如果您仍想保留它,那么在AJAX中也包含它作为test / rest / ping