In this tutorial how to create a simple login page using Session object JSP page is shown.
Code:
index.html
<html>
<head>
<title>Login</title>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
</head>
<body>
<form action=”Login.jsp” method=”POST”>
Username: <input type=”text” name=”uname”><br>
Password: <input type=”password” name=”pwd”><br>
<input type=”submit” value=”Login”>
</form>
</body>
</html>
Login.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>JSP Page</title>
</head>
<body>
<%
String uid=request.getParameter(“uname”);
String pwd=request.getParameter(“pwd”);
session.setAttribute(“session-uid”, uid);
if(uid.equals(“John”) && pwd.equals(“Admin”))
{
response.sendRedirect(“success.jsp”);
}
else
{
response.sendRedirect(“fail.jsp”);
}
%>
</body>
</html>
success.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>Success</title>
</head>
<body>
<%
String uid=(String)session.getAttribute(“session-uid”);
out.println(“Welcome “+uid+” !!”);
%>
</body>
</html>
fail.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>Fails</title>
</head>
<body>
<%
String uid=(String)session.getAttribute(“session-uid”);
out.println(“Sorry “+uid+” Username or Password is incorrect!!”);
out.println(“<a href=’index.html’>Click Here</a> to go to Login Page”);
%>
</body>
</html>