使用Jquery AJAX使用JSON参数的Spring REST Web服务

时间:2015-11-03 09:22:27

标签: java jquery json ajax spring

我正在尝试学习Spring Framework,为我未来的项目创建RESTful Web服务。到目前为止,我已经尝试使用GET并使用简单的Ajax请求使用它没有问题。我也尝试使用查询字符串输入参数。

截至目前,我正在尝试创建一个接收POST请求的端点。我现在已经研究了几天但是没有用(对于像我这样的初学者来说,有些因素太复杂了。)

这是我的简单代码:

Java Spring

@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public String testString(String jsonString)
{
        System.out.println(jsonString);
        return jsonString;
}

的Ajax

  var data = {"name":"John Doe"}
  $.ajax({
              url: "http://localhost:8080/springrestexample/test",
              method:"POST",
              data:data,
              dataType:'text',
              success: function( data ) {
                 alert(data);                                 
              },
              error: function( xhr, status, errorThrown ) {
                  alert("Error:" + errorThrown + status);
              }
      });

我试过调试tomcat,好像我没有在testString上传递任何值。我需要在我的java代码上添加一些内容吗?

2 个答案:

答案 0 :(得分:0)

@RequestMapping仅将您的方法映射到某个网址。 要访问数据,您需要@RequestParam注释来获取数据,例如:

@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public String testString(@RequestParam("name") String jsonString)
{
    System.out.println(jsonString);
    return jsonString;
}

查看this手册以获取更多示例。

答案 1 :(得分:0)

Since you are passing data into body from your ajax request, so you need to retrieve from the

@RequestBody

Add this annotation before the arguments like this way;

public string lang { get; set; }

And you are done :)

相关问题