这是我的Java代码和HTML代码。
当用户点击“重定向”按钮时,我想将他重定向到登录页面并终止当前会话。我已成功完成重定向部分,但我不知道如何终止会话。我想在HTML中的action =中使用session.invalidate。可以这样做吗?如果没有,那么最好的选择是什么? THX。
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.*;
@WebServlet("/test1")
public class test1 extends HttpServlet{
public void init(){
System.out.println("init is called");
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();// used to type in the browser
String s=req.getParameter("username");
String s2=req.getParameter("pwd");
// Create a session object if it is already not created.
HttpSession session = req.getSession(true);
if(s.equals("ace")&& s2.equals("123"))
{
//pw.println("<h1>"+"Welcome to the world of servlets "+s+"</h1>");
String title= "Welcome to the world of servlets: "+s;
String s3="The session id is: "+session.getId();
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
pw.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h1 align=\"center\">" + s3 + "</h1>\n"+
"<ul>\n" +
"<input type=\"button\" onclick=\"location.href('http://localhost:8080/AkshayServlet2/test.html');\" value=\"Redirect\">"+
"</ul>\n" +
"</body></html>");
session.invalidate();
//System.out.println.print("You have logged out");
}
else
{
pw.println("Please enter the correct username and password");
req.getRequestDispatcher("test.html").include(req, res);;
}
}
public void destroy(){
System.out.println("calling destroy method");
}
}
HTML code:
<html>
<body>
<form action="test1" method=get> <!-- we use xy because we used xy in the url in web.xml. We have to map it to the url -->
Enter UserName: <input type=text name=username><br>
Enter Password: <input type=password name=pwd><br>
<input type=submit value="Login">
</form>
</body>
</html>
答案 0 :(得分:1)
您必须调用HttpServletRequest :: getSession方法,以便创建新会话以替换先前无效的会话。
在会话失效行之后添加以下代码:
req.getSession(true);