立即重定向。为什么会这样?

时间:2012-08-24 08:31:37

标签: java javascript jsp

我试图将用户从一个jsp页面重定向到另一个jsp页面后让他等待10秒或10000毫秒。但是一旦在浏览器中打开页面,就会有重定向。为什么会这样?以下代码有什么问题吗?我正在调用redirectFunction进行重定向。

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP - 1</title>
    <script>
        function redirectFunction() {
            <% response.sendRedirect("jsp-2.jsp"); %>
        }
    </script>
</head>

<body>
    <h1>
        Wait while you are redirected...
    </h1>
    <script type="text/javascript"> 
        setTimeout(redirectFunc,10000); // wait for 10 seconds,then call redirectFunc
    </script>
</body>

5 个答案:

答案 0 :(得分:1)

您完全从服务器发送重定向,这就是它立即解雇的原因。

如果您想在10秒后触发重定向而不是需要更改代码:

function redirectFunction() {
    window.location.href = "jsp-2.jsp"
}

setTimeout(redirectFunction,10000);

实际上当你调用<% response.sendRedirect("jsp-2.jsp"); %>时,Java服务器将http代码302设置为你的http响应,并且标题位置:jsp-2.jsp 浏览器会立即重定向到Location头中指定的页面。

希望它有所帮助。

答案 1 :(得分:1)

scriptlet中的代码在服务器上执行,它不是javascript。使用这个

function redirectFunction() {
            window.location.href = "jsp-2.jsp";
}

答案 2 :(得分:0)

假设您正在使用HttpServletResponse,发生的情况是您发送的HTTP位置标头的状态代码为302.这是在请求页面时发生的,而不是在客户端执行JavaScript时发生的。

如果您希望在JavaScript执行期间使用它,则需要将您想要的URL分配给window.location。

window.location = "http://google.com";

例如

答案 3 :(得分:0)

这是因为

 <script>
        function redirectFunction() {
            <% response.sendRedirect("jsp-2.jsp"); %>
        }
 </script>

被翻译并执行为

out.print(" <script> function redirectFunction() {");
response.sendRedirect("jsp-2.jsp");
out.print("</script>");

答案 4 :(得分:0)

调用sendRedirect在服务器端执行,同时准备页面,并执行重定向。您可以使用window.location仅在javascript中进行睡眠和重定向。