我试图在让用户等待 10 秒或 10000 毫秒后将用户从一个 jsp 页面重定向到另一个 jsp 页面。但是,一旦在浏览器中打开页面,就会发生重定向。为什么会这样呢?下面的代码有什么问题吗?我正在调用执行重定向的 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>
最佳答案
您完全从服务器发送重定向,这就是它立即触发的原因。
如果您想在 10 秒后触发重定向,则需要更改代码:
function redirectFunction() {
window.location.href = "jsp-2.jsp"
}
和setTimeout(redirectFunction,10000);
实际上当你调用<% response.sendRedirect("jsp-2.jsp"); %>
时Java 服务器将 http 代码 302 设置为您的 http 响应,并且 header 位置:jsp-2.jsp
浏览器立即重定向到 Location header 中指定的页面。
希望有帮助。
关于java - 立即重定向。为什么会这样呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12105760/