简体   繁体   English

JSP:倒数计时器不起作用?

[英]JSP: Countdown timer not working?

GET METHOD: 获取方法:

 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);
        }
    }

Specifically this part: 特别是这部分:

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

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

Countdown class: 倒数班:

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;
    }
}

And the interface: 和界面:

public interface OnWaiting {
    public void onFinished();

}

Why doesn't this work in a JSP? 为什么这在JSP中不起作用? It works under a regular java project. 它在常规的Java项目下工作。 I want to do this via java not javascript in the JSP. 我想通过Java而不是JSP中的javascript来做到这一点。

It doesn't work because once the servlet Get method finishes the communication with the client is closed. 它不起作用,因为一旦Servlet Get方法完成与客户端的通信,它就会关闭。 HTTP is normally a Request-response protocol with the exception of Websockets therefore sending anything to the response once it's finished won't have any effect. HTTP通常是请求-响应协议, Websockets除外,因此,一旦响应完成,将任何内容发送到响应都将无效。

You can try an ajax request after the page is loaded. 页面加载后,您可以尝试ajax请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM