2011-05-22 43 views
2

我使用碼頭-7.4.1.v20110513和servlet-API-2.5碼頭7延續

我試圖在以下的servlet使用continations。

import java.io.*; 
import java.util.*; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

import org.eclipse.jetty.continuation.*; 



public class cs extends HttpServlet { 

public void service(HttpServletRequest req, HttpServletResponse res) 
throws java.io.IOException { 

String reqId = req.getParameter("id"); 

Continuation cc = ContinuationSupport.getContinuation(req); 

res.setContentType("text/plain"); 
res.getWriter().println("Request: "+reqId+"\tstart:\t"+new Date()); 
res.getWriter().flush(); 

cc.setTimeout(2000); 
cc.suspend(); 

res.getWriter().println("Request: "+reqId+"\tend:\t"+new Date()); 
cc.complete(); 
} 
} 

我期待一個2秒的延遲,但是當我從瀏覽器中運行該servlet我得到的輸出如下沒有任何延遲:

Request: null start: Sat May 21 15:25:02 IST 2011 
Request: null end: Sat May 21 15:25:02 IST 2011 

回答

1

我終於想通了延續API。下面的代碼爲我工作。感謝您的支持人員。

import java.io.*; 
import java.util.*; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

import org.eclipse.jetty.continuation.*; 

public class cs extends HttpServlet { 

    public void doGet(HttpServletRequest req, HttpServletResponse res) 
     throws java.io.IOException { 

    String reqId = req.getParameter("id"); 

    Continuation cc = ContinuationSupport.getContinuation(req); 

    res.setContentType("text/plain"); 
    res.getWriter().println("Request: " + reqId + "\tstart:\t" + new Date()); 
    res.getWriter().flush(); 

    cc.setTimeout(2000); 
    cc.suspend(); 

    res.getWriter().println("Request: " + reqId + "\tend:\t" + new Date()); 
    if (cc.isInitial() != true) { 
     cc.complete(); 
    } 
    } 
} 

輸出:

Request: null start: Sat May 21 15:25:02 IST 2011 
Request: null end: Sat May 21 15:25:02 IST 2011 
Request: null start: Sat May 21 15:25:04 IST 2011 
Request: null end: Sat May 21 15:25:04 IST 2011 
1

我想你正在讀這篇tutorial。 A 2秒的延遲可以通過以下方法之一來實現:

  • 要麼第二res.getWriter().println()之前添加Thread.sleep(2000)

  • 或刪除Continuation.complete()調用將使延續等待Continuation.setTimeout()中指定的最長時間。現在會發生什麼是你立即你的「計算」完成通知(通過調用cc.complete()