我要在servlet中创建一个会话,并通过requestDispatcher将其发送到下一个servlet或jsp页面。 但是问题在于它不应该在另一个选项卡中。 如果创建了会话,则应在下一个选项卡中显示该会话,但是当我在下一个选项卡中输入URL时,它将显示一个空白页面。 我不知道为什么?请向我解释为什么会发生这种情况。
Home.jsp
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<%
out.println("Name ::" + session.getAttribute("name"));
if (session.getAttribute("name") != null) {
// response.sendRedirect("Main.jsp");
response.sendRedirect("WelcomeServlet");
//request.getRequestDispatcher("WelcomeServlet").forward(request, response);
}
%>
<div style="width: 200px;height: 100px;border: 1px solid black;padding: 80px;margin: 50px 200px;">
<form action="DispacherDemo" method="POST">
<input type="text" name="user" placeholder="NAME"/><br/><br>
<input type="password" name="pass" placeholder="PASSWORD"><br/><br>
<input type="submit" value="submit">
</form>
</div>
</body>
</html>
Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Hello world!!!!");
try {
HttpSession session = request.getSession();
out.println("SESSIONID"+session.getId()+" Name "+session.getAttribute("name"));
String name = request.getParameter("user");
String password = request.getParameter("pass");
if ((password.equals("pass") && name.equals("vinay"))||session.getAttribute("name")!=null) {
if(session.getAttribute("name")!=null){
out.println("Servlet session=="+session.getAttribute("name"));
RequestDispatcher rd = request.getRequestDispatcher("WelcomeServlet");
rd.forward(request, response);
}else{
session.setAttribute("name", name);
RequestDispatcher rd = request.getRequestDispatcher("WelcomeServlet");
rd.forward(request, response);
}
} else {
out.println("<font color='red'><b>You have entered incorrect password</b></font>");
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.include(request, response);
}
} finally {
out.close();
}
}
WelcomeServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
HttpSession session = request.getSession(false);
try {
out.println("Name::::"+session.getAttribute("name"));
if (session.getAttribute("name")==null) {
out.println("You have to login first!!!!");
response.sendRedirect("index.html");
} else {
String name = (String) session.getAttribute("name");
out.println("<h2>Welcome " + name + " " + session.getId() + "</h2>");
out.println("<br/><a href=\"logoutServlet\">Logout</a>");
}
} finally {
out.close();
}
}
如果创建会话,则页面也应该对另一个选项卡可见。