JSP:倒计时器不起作用?

时间:2014-04-20 00:49:19

标签: java jsp

获取方法:

 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项目下工作。我想通过JSP中的java而不是javascript来做到这一点。

1 个答案:

答案 0 :(得分:0)

它不起作用,因为一旦servlet Get方法完成与客户端的通信关闭。 HTTP通常是Request-response协议,但Websockets除外,因此在响应完成后向响应发送任何内容都不会产生任何影响。

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