我对GWT有一个不寻常的问题。我在浏览器上编译项目后运行它来运行.html文件。它运行正常,直到出现以下代码行:
public static ClickHandler addBoardButtonHandler(final String name) {
return new ClickHandler(){
@Override
public void onClick(ClickEvent event) {
Window.alert("We will retrieve them!"); //this line runs
String boardSTickets = getBoardSTickets(name); // this too
Window.alert("We got tickets!"); // the code is never executing this line
String boardSSwimlanes = getBoardSSwimlanes(name);
Window.alert("We got swimlanes!");
KanbanizerClient.showSingleBoard(boardSTickets, boardSSwimlanes);
}
};
}
此方法由另一种方法调用:
private static Button addBoardButton(String name) {
Button button = new Button(name);
button.addClickHandler(HandlerManager.addBoardButtonHandler(name));
return button;
}
哪个也正常运行。这是getBoardSTickets()方法:
protected static String getBoardSTickets(String name) {
final List<String> ticketsJSON = new LinkedList<String>();
try {
Request request = Builder.createBuilder(RequestBuilder.GET, "http://localhost:8080/Kanbanizer/boards/" + name + "/tickets").sendRequest(null, new RequestCallback(){
@Override
public void onResponseReceived(Request request,
Response response) {
if(response.getStatusCode() == 200){
ticketsJSON.add(response.getText());
}
}
@Override
public void onError(Request request, Throwable exception) {
// TODO Auto-generated method stub
}
});
} catch (RequestException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ticketsJSON.get(0);
}
谢谢:)
答案 0 :(得分:2)
了解GWT环境中的ajax - 请阅读https://developers.google.com/web-toolkit/doc/latest/tutorial/clientserver
中的“拨打异步电话”部分将getBoardSTickets()编程为执行异步请求调用后返回字符串的方法是有缺陷的。不要尝试在getBoardSTickets()中返回异步调用的结果。
在return ticketsJSON.get(0);
之后立即调用 sendRequest()
。它会引发异常,因为ticketJSON将没有条目,因为RequestCallback()不会完成处理。
尝试从外部传递回调
protected static String getBoardSTickets(String name, RequestCallback callback){
//Code for making request
}
您的调用代码应更改为
getBoardSTickets(name, new RequestCallback(){
//onSuccess and onFailure handling.
} )
对于调用异步调用服务器的所有方法,同样的逻辑也适用。您不应该编程以从方法返回请求响应的值。