For your help i have written an example and executed the code in my machine.
In servlet page, in doPost
:
String username = request.getParameter("username");
String password = request.getParameter("password");
boolean isCredentialValid = validateCredentials(username, password);
String nextPage ="";
HttpSession session = request.getSession(true);
if(isCredentialValid){
nextPage = "home.jsp";
session.setAttribute("isLoggedIn", "true");
}else{
request.setAttribute("error", "Either username or password is invalid.");
nextPage ="login.jsp";
}
RequestDispatcher rd = request.getRequestDispatcher(nextPage);
rd.forward(request, response);
in login.jsp
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
var isLoggedIn = "<%= (String)session.getAttribute("isLoggedIn")%>";
if(isLoggedIn === "true")
window.location.href="home.jsp";
}
</script>
</head>
<body>
<form action="Test" method="post">
${error}
<br/>
UserName : <input type="text" name="username"/>
<br/>
Password : <input type="text" name="password"/>
<br/>
<input type="submit" value="submit"/>
</form>
</body>