I have developed a login page where the user id and minmum password length validation is done by JavaScript and I have a servlet that connects to DB and authenticates the user. Can someone please tell me how to display a message in the same login page when authentication fails?
5 Answers
Send a flag value of login failed from your servlet like this.
request.setAttribute("loginResult", true);
Now get this value in JSP. Its default value will be false. if its true then show error message.
<%
if(request.getAttribute("loginResult") != null && request.getAttribute("loginResult") == "true"){
%>
<p style="color:red"> Login Failed. Please try again. </p>
<%
}
%>
For Javascript call a function to show error, instead of <p style="color:red"> Login Failed. Please try again. </p>
from my above code.
-
After
req.setAttribute("loginResult", true)
operation in servlet, should I forward the request back to the JSP page? Like here:RequestDispatcher rd = req.getRequestDispatcher("login.jsp"); rd.forward(req, response);
Jan 14, 2016 at 18:50
HTML (place this in the page's HTML where the error message should be displayed):
<span id="login_failed"></span>
JavaScript:
<script type="text/javascript">
var login_success = false; /* set this to true if the login was a success */
if(login_success == false)
{
document.getElementById("login_failed").innerHTML = "Login Failed.";
}
else
{
window.location = "http://www.yourpage.com/login_success.html";
}
</script>
in your web.xml put this
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/login.jsp?loginerror=100</form-error-page>
</form-login-config>
</login-config>
now in your login.jsp put this javascript to read the loginerror param and call it ondocument.ready (onload())
function gup()
{
var name = 'loginerror';
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
//here you don't have login errors
else
//here you have login error
}
enjoy
Print the JavaScript in Servlet.
The alert message:
System.out.println("<script>alert('Login fail.')</script>");
Redirect to login page again:
System.out.println("<script>window.location='loginUrl'</script>");