Reputation: 63
I have a login page with a login servlet in which if the user enters wrong credentials, an alert is given:
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<script type=\"text/javascript\">");
out.println("alert('User or password incorrect, please try again');");
out.println("</script>");
out.println("</head>");
out.println("</html>");
the alert works fine, but after alert, it gives a blank page with the link :
http://localhost:8080/AWSCustomerJavaWebFinal/LoginServlet
What is the possible solution for this, so that after the alert, the page stays on login.jsp or forwards to login.jsp after the alert, rather than moving forward to the login servlet, I tried request dispatcher but then it did not show the alert and moved to login.jsp again.
Upvotes: 0
Views: 1086
Reputation: 13858
If you insist of showing an alert to the user as a result of this POST
operation, you should consider doing the redirect in javascript as well:
out.println("<script type=\"text/javascript\">");
out.println("alert('User or password incorrect, please try again');");
out.println("window.location = 'login.jsp';");
out.println("</script>");
You might also want to think about adding at least a basic <body> to that response.
Upvotes: 1
Reputation: 44834
The basic idea is that when you POST a form to a servlet, the servelt will validate the data. if it fails then the servlet will add an attribute to the session and redirect back to the jsp page, other wise it will redirect to the main page
In all cases the JSP will check for this session attribute, if it does not exist, then it means it is normal (first try login) otherwise it means it has tried before and failed and it will display the error.
if you really really want an alert, then set a hidden field (with a html id) with the value of this session attribute. The Javascript (onLoad/ready) will check this html element and display an alert if necessary.
Upvotes: 2
Reputation: 8652
When you submit your form, you gave a url in action
attribute. On submission the form will be sent to that url. Which means you are now directed to that url. So it will stay on the url you provided.
Either provide same action url (login.jsp) and if authenticated then redirect user to another page
Or use ajax to do this stuff.
Upvotes: 0