我有一个项目,您可以以jax-rs
格式请求json
提供的资源。当我查询其余URL时,json
会在浏览器中正常运行。
现在,我希望我的GWT项目请求这些资源并对其进行处理,并在界面中显示它们。我发现这样做的最简单方法是使用请求生成器和覆盖图。代码较低。问题是,似乎在代码运行时,它永远不会进入实际的RequestCallback()中。状态字符串永远不会更改。我以为可能是SOP,所以我添加了<add-linker name="xs"/>
,但仍然无法正常工作。有理想吗?
package com.workoutcell.client;
//import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.http.client.*;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
/**
*
* @author
*/
public class RestToInfoSession{
String queryReturn = null;
JsArray<InfoJSO> arrayOfInfo = null;
String host = "http://localhost:8080/mysite";
String restModule = "/calendar/getinfo";
String id = null;
String year = null;
String month = null;
String status = "Not Initialized";
public RestToInfoSession(String id, String year, String month){
this.id =id;
this.year = year;
this.month = month;
String url = host + restModule + "/"+this.id + "/"+this.year + "/"+this.month;
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
status = "Initialized at Url " + builder.getUrl();
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// Couldn't connect to server (could be timeout, SOP violation, etc.)
status = "Error on connecting to Server";
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
// arrayOfInfo = jsonToJsArray(response.getText());
status = "JSON has been Fetched. Result is:" + response.getText();
} else if(0 == response.getStatusCode()) {
status = "Error is 0";
} else {
status = "Error in JSON Request:" + response.getStatusCode();
//response.getStatusText();
}
}
});
} catch (RequestException ex) {
status = "Error in Request Builder Startup";
}
}
//get an jso object in array
private final native JsArray<InfoJSO> jsonToJsArray(String json) /*-{
return eval(json);
}-*/;
public JsArray<InfoJSO> getInfoArray (){
return arrayOfInfo;
}
}
更新:我的问题和Referring to a non-final variable data inside an inner class相同。我不知道异步调用的工作机制。我仍然不知道如何通过response.getText()
更新不属于RestToInfoSession类的标签的任何想法?
考虑使用RestyGWT项目。它将使调用JAXRS JSON资源像使用GWT-RPC一样容易。另外,您通常可以从客户端的服务器端重用相同的请求响应DTO。
我放置了一个计时器,每隔1000毫秒检查一次我的json字符串是否已从null更新为xhttp请求的数据。这可行,但我感觉有解决该问题的更优雅的方法。