获取方法:

 protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // Writes to htmlPage
        final PrintWriter writer = response.getWriter();
        // init CountDownTimer TODO: Understand why this doesn't work
        CountdownTimer timer = new CountdownTimer(CountdownTimer.toMili(5));
        timer.start(new OnWaiting() {

            @Override
            public void onFinished() {
                writer.println("Timer Finished");
            }
        });
        // getting params from url '?'
        final String userName = request.getParameter(USER_NAME);
        final String passWord = request.getParameter(PASS_WORD);
        // authentication step
        if (isValidUser(userName, passWord)) {
            writer.println(VALID);
        } else {
            writer.println(INVALID_USER_NAME + " or " + INVALID_PASS_WORD);
        }
    }

特别是这部分:

CountdownTimer timer = new CountdownTimer(CountdownTimer.toMili(5));
        timer.start(new OnWaiting() {

            @Override
            public void onFinished() {
                writer.println("Timer Finished");
            }
        });

倒数班:

public class CountdownTimer {
    private final int mili;

    public CountdownTimer(int mili) {
        this.mili = mili;
    }

    public void start(final OnWaiting waiting) {
        final Thread thread = new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(mili);
                    waiting.onFinished();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }

    public static final int toMili(int seconds) {
        return seconds * 1000;
    }
}

和界面:

public interface OnWaiting {
    public void onFinished();

}

为什么这在JSP中不起作用? 它在常规的Java项目下工作。 我想通过Java而不是JSP中的javascript来做到这一点。

===============>>#1 票数:0 已采纳

它不起作用,因为一旦Servlet Get方法完成与客户端的通信,它就会关闭。 HTTP通常是请求-响应协议, Websockets除外,因此,一旦响应完成,将任何内容发送到响应都将无效。

页面加载后,您可以尝试ajax请求。

  ask by horvste translate from so

未解决问题?本站智能推荐: