JSP Login and Logout System Example Using Session
1)
index.jsp
<html>
<head>
<title>Login System</title>
</head>
<body>
<%
String email=(String)session.getAttribute("email");
//redirect user to home page if already logged in
if(email!=null){
response.sendRedirect("home.jsp");
}
String status=request.getParameter("status");
if(status!=null){
if(status.equals("false")){
out.print("Incorrect login details!");
}
else{
out.print("Some error occurred!");
}
}
%>
<form action="loginRequestHandler.jsp">
<table cellpadding="5">
<tr>
<td><b>Email:</b></td>
<td><input type="text" name="email" required/></td>
</tr>
<tr>
<td><b>Password:</b></td>
<td><input type="password" name="password" required/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Login"/></td>
</tr>
</table>
</form>
</body>
</html>
2)
loginRequestHandler.jsp
<%@page import="com.LoginDAO"%>
<jsp:useBean id="loginBean" class="com.LoginBean" scope="session"/>
<jsp:setProperty name="loginBean" property="*"/>
<%
String result=LoginDAO.loginCheck(loginBean);
if(result.equals("true")){
session.setAttribute("email",loginBean.getEmail());
response.sendRedirect("home.jsp");
}
if(result.equals("false")){
response.sendRedirect("index.jsp?status=false");
}
if(result.equals("error")){
response.sendRedirect("index.jsp?status=error");
}
%>
3)home.jsp
<html>
<head>
<title>Login System</title>
</head>
<body>
<%
String email=(String)session.getAttribute("email");
//redirect user to login page if not logged in
if(email==null){
response.sendRedirect("index.jsp");
}
%>
<p>Welcome <%=email%></p>
<a href="logout.jsp">Logout</a>
</body>
</html>
4)
logout.jsp
<%
session.invalidate();
response.sendRedirect("index.jsp");
%>
Sign up here with your email
ConversionConversion EmoticonEmoticon