24.Session Management in servlet


Html-page

<html>
<head>
<title></title>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<fieldset>
<legend>Login App using HttpSession</legend>

<a href=”login.html”>Login</a>|
<a href=”LogoutServlet”>Logout</a>|
<a href=”ProfileServlet”>Profile</a>
</fieldset>
</body>
</html>

Login.html
<html>
<head>
<title></title>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<form action=”LoginServlet” method=”post”>
Name:<input type=”text” name=”name”><br>
Password:<input type=”password” name=”password”><br>
<input type=”submit” value=”login”>
</form>
</body>
</html>

Loginservlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8”);
PrintWriter out = response.getWriter();
try {
String name=request.getParameter(“name”);
String password=request.getParameter(“password”);
request.getRequestDispatcher(“link.html”).include(request, response);
if(password.equals(“admin123”)){
out.print(“Welcome, “+name);
HttpSession session=request.getSession();
session.setAttribute(“name”,name);
}
else{
out.print(“Sorry, username or password error!”);
request.getRequestDispatcher(“login.html”).include(request, response);
}
} finally {
out.close();
}
}

Logoutservlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8”);
PrintWriter out = response.getWriter();
try {
request.getRequestDispatcher(“link.html”).include(request, response);

HttpSession session=request.getSession();
session.invalidate();

out.print(“You are successfully logged out!”);

} finally {
out.close();
}
}
Profileservlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8”);
PrintWriter out = response.getWriter();
try {
request.getRequestDispatcher(“link.html”).include(request, response);

HttpSession session=request.getSession(false);
if(session!=null){
String name=(String)session.getAttribute(“name”);

out.print(“Hello, “+name+” Welcome to Profile”);
}
else{
out.print(“Please login first”);
request.getRequestDispatcher(“login.html”).include(request, response);
}
} finally {
out.close();
}
}