3

我正在编写一个 servlet,它在现有的 java 系统(“MyJavaSystem”)上运行命令并将输出写入用户。执行的命令是异步的,servlet 必须将每个结果行返回给客户端。我正在使用 Jetty 和 Continuation。

这是我的代码:

public class MyServlet extends HttpServlet {
    private static final long timeoutMs = 6000;
    public MyJavaSystem sys;
    Continuation continuation = null;

    public MyServlet (MyJavaSystem a) { sys = a; }

    @Override
    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException  {
        String commandResult = (String)request.getAttribute("results");
        if (commandResult == null)
        {       
            continuation = ContinuationSupport.getContinuation(request);
            if (continuation.isInitial())
            {
                continuation.setTimeout(timeoutMs);
            }
            if (continuation.isExpired()) 
            {
                response.getWriter().write("Timeout");
                return;
            }       
            if ( request.getParameter("command") != null && ! request.getParameter("command").equals("") ) 
            {
                // Execute command
                sys.execute(request.getParameter("command"));

                // suspend the request
                continuation.suspend();

                // ---- Here I need to register myHandler and myHandler2
            }
        } else {
            // Write command result line to user
            response.getWriter().write(commandResult); 
            continuation.complete();
        }

    }
    // Called by sys every new line in command output
    public void myHandler(String commandOutput)
    {
        if (continuation != null)
        {
            continuation.setAttribute("results",commandOutput);
            continuation.resume();
        }
    }
    // Called by sys when the command is done
    public void myHandler2(String commandOutput)
    {
        if (continuation != null)
        {
            continuation.setAttribute("results",commandOutput);
            continuation.complete();
        }
    }
}

sys.execute() 是非阻塞调用(由于系统实现),myHandler()、myHandler2() 函数将在命令执行期间由外部 java sys 调用。

我怎样才能注册这个处理程序?如果我运行上面的代码,我会得到:

    FATAL EXCEPTION: Thread-726
    java.lang.IllegalStateException: IDLE, initial 
    at org.eclipse.jetty.server.AsyncContinuation.dispatch(AsyncContinuation.java:427)
    at org.eclipse.jetty.server.AsyncContinuation.resume(AsyncContinuation.java:892) 
    at mypackage.MyServlet.myHandler(MyServlet.java:22)
4

0 回答 0