我无法解释 sendRedirect 函数的这个奇怪问题。 我有一个 header page 作为 Header.jsp 作为:
<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*,java.util.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Online Exam Portal</title>
<style type="text/css">
body{
background-color : lightgreen;
}
</style>
</head>
<body>
<%
if(session.getAttribute("userid")==null)
{
response.sendRedirect("signup.html");
}
%>
<img src="exam_header01.jpg"/>
<br />
Welcome <%=session.getAttribute("userid")+"This is Working"%>
<a href="ChangePassword.jsp">Change Password</a>
<a href="logout.jsp">Logout</a>
<hr/>
我在所有页面中都包含这个标题页,我这样做是因为我想阻止没有有效 session 的用户重定向到注册页面,但它没有' t 重定向
相反,它显示 Welcome null 和 :
1> 如果我在 if 语句中写任何东西,它就可以正常工作! ,比如:
if(session.getAttribute("userid")==null)
{
response.sendRedirect("signup.html");//this is not executed
out.println("This Runs");//this String is printed
}
2> 如果我在主页中(即在标题页之后)编写相同的代码,它工作正常!
3> 最重要的是,当我将代码替换为:
<jsp:forward page="signup.html"/>
这里可能是什么问题。如果有人能举例说明,我们将不胜感激。
更新 :- 即使我在重定向后打印到我的页面,如果我在包含标题后使用 if 语句,它也会工作:
<jsp:include page="Header.jsp"/>
<%if(session.getAttribute("userid")==null)
{
response.sendRedirect("signup.html");
out.println("I cant See this because page is redirected ");
}
%>
</body>
</html>
最佳答案
正如其他人所说,这不是实现您想要实现的目标的最佳方式。
也就是说,您看到的问题是由于使用了错误的包含类型。您正在使用请求时间包含 ( <jsp:include page="..." />
),它处理包含的页面并将输出(如果有)插入当前页面。如果您调用 response.sendRedirect()
从包含的页面中它被忽略。因此,您当前的解决方案不起作用。
您需要使用翻译时间包含 ( <%@ include file=... %>
),它获取包含页面的源代码,将其插入当前页面的源代码中,然后像处理单个 JSP 一样处理当前页面。
关于java - sendRedirect() 函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20454598/