繁体   English   中英

如何在Restful Web服务中从Ajax调用捕获数据参数?

[英]How to capture data parameter from Ajax call in Restful webservice?

我有一个ajax调用,我在调用传递字符串的Restful WS-

var b2bValues = "Some String";  
var lookupUrl = "http://ip:{port}/ImageViewer/rest/ImageServlet/callrest";  
var lookupReq = $.ajax({url:lookupUrl, async:false, data:b2bValues, contentType: "application/xml", type: "POST"});

我的Restful代码是-

@POST
@Path("/callrest")
@Consumes({"application/xml", "application/json", "text/plain"})
@Produces({"application/xml", "application/json", "text/plain"})
public ImageFieldsList getImageFromSource(@QueryParam("b2bValues") String b2b)
{//Some code
}

服务器端的b2bValues为空。

我的问题是如何更改Restful代码以捕获从Ajax调用传递的数据参数?

有两种方法可以解决此问题

  1. @QueryParam将在请求URL中查找可用的参数。 因此,如果需要在服务器端使用@QueryParam ,则需要修改URL并发送数据,如下所示:

     var b2bValues = "Some String"; var lookupUrl = "http://ip:{port}/ImageViewer/rest/ImageServlet/callrest?b2bValues="+b2bValues; var lookupReq = $.ajax({url:lookupUrl, async:false, contentType: "application/xml", type: "POST"}); 

    在这种情况下,不需要在服务器端进行任何更改。

  2. 通常,对于POST请求,我们通过形成请求对象来发送数据。 因此,在客户端,您将像这样形成请求对象:

     var requestData = { b2bValues : "SomeValue", someOtherParam : "SomeOtherParamValue", anotherParam : "AnotherParamValue" } var lookupReq = $.ajax({url:lookupUrl, async:false, data:JSON.stringify(requestData), contentType: "application/xml", type: "POST"}); 

    在服务器端,您将需要具有等效值的对象来保存请求数据。 成员变量的名称应与您在请求中发送的名称匹配(反之亦然)

    样品请求对象

     // SampleRequestObject.java String b2bValues; String someOtherParam; String anotherParam; // getters and setters for these member variables 

    现在,ReST方法将更改为:

     @POST @Path("/callrest") @Consumes({"application/xml", "application/json", "text/plain"}) @Produces({"application/xml", "application/json", "text/plain"}) public ImageFieldsList getImageFromSource(SampleRequestObject requestInput) { // access request input using getters of SampleRequestObject.java // For example, requestInput.getB2bValues(); } 

需要更改服务器代码-

@POST
@Path("/callrest")
@Consumes({"application/xml", "application/json", "text/plain"})
@Produces({"application/xml", "application/json", "text/plain"})
public ImageFieldsList getImageFromSource(String b2bValues)
{//Some code
}

无需使用@Queryparam,但键应与变量名匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM