我有一个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调用传递的数据参数?
答案 0 :(得分:2)
有两种方法可以解决问题
@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"});
在这种情况下,服务器端不需要进行任何更改。
通常,对于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();
}
答案 1 :(得分:0)
需要更改服务器代码 -
@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,但密钥应与变量名匹配。