(從服務器上的一個servlet)
要呼叫,而不使用HTML代碼調用servlet的入隊,你用RequestDispatcher的和向前請求。
String enqueueURL = "/enqueue";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(destination);
dispatcher.forward(request, response);
要發送列表到另一個servlet,使用了request.setAttribute
request.setAttribute("myList", list);
要獲得它在不同的servlet,使用request.getAttribute
List value = (List)request.getAttribute("myList")
從從設計的角度來看,如果你的servlet作爲一個控制器發揮作用,比如在Model-View-Controller系統中, ñ它的使用是適當的。
(從GWT客戶端代碼)
簡單地使一個RPC調用,並在處理方法是把你的隊列代碼:
public class MyServiceImpl extends RemoteServiceServlet implements
MyService {
public void myMethod(String key) {
Queue queue = QueueFactory.getDefaultQueue();
byte[] buf;
TaskOptions taskOptions= TaskOptions.Builder.withUrl("/tasks/worker").method(Method.POST);
taskOptions.payload(buf);
queue.add(taskOptions);
}
}
如果您需要幫助將列表轉換爲字節[],請參閱this or something like it (i.e. coverting a Java Object to an byte[] array ..don't forget to include a cast to get it back into a List)
撥叫的GWT客戶端代碼一個servlet,只需使用一個RequestBuilder
import com.google.gwt.http.client.*;
...
String url = "http://www.myurl.com/enqueue";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
try {
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.)
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
// Process the response in response.getText()
} else {
// Handle the error. Can get the status text from response.getStatusText()
}
}
});
} catch (RequestException e) {
// Couldn't connect to server
}
見GWT Docs on RequestBuilder
感謝您的寶貴意見,但In GWT我們不能使用RequestDispatcher –
其實我想調用Enqueue sevlet而不使用html代碼,如https://cloud.google.com/appengine/docs/java/taskqueue/overview-push那麼我怎樣才能從用戶調用Enqueue servlet請求 –
RequestDispatcher將在一個servlet中運行,並且應該在GWT中正常工作。它不在客戶端代碼中運行。要從客戶端代碼調用,只需使用RPC調用,然後在處理ServiceImpl類中的調用的方法中調度任務。否則,你可以從GWT客戶端代碼中調用一個servlet,但是如果你已經使用了RPC調用,那就更容易了。 – user1258245