For login example we are using user mail id and password. if both are correct then we are forwaring to home.jsp page if any on of mail id or password is in correct then it will forwarded back to index.jsp page with appropriate error message.
index.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Login Page</title> </head> <body> <h1>Login Page</h1> <div style="color: red"> <% String message = (String) request.getAttribute("error"); if(message!=null){ out.println(message); } %> </div> <form action="login" method="post"> Mail Id : <input type="text" name="mailId" placeholder="Enter your mail id"/><br><br> Password : <input type="password" name="password" placeholder="Enter your password"/><br><br> <input type="submit" value="Login"/> </form> </body> </html> |
Login.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | package ebhor.servlet; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name = "Login", urlPatterns = {"/login"}) public class Login extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String mailId = request.getParameter("mailId"); String password = request.getParameter("password"); System.out.println("Mail id "+mailId+" password "+password); System.out.println("Successfully Login"); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/home.jsp"); dispatcher.forward(request, response); } else { System.out.println("Mail id or password is incorrect"); request.setAttribute("error", "Please enter correct username and/or password"); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); } } } |
home.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Home Page</title> </head> <body> <h1>Welcome User</h1> <h3>Your mail id is <%=request.getParameter("mailId")%></h3> <h3>Your password is <%=request.getParameter("password")%></h3> </body> </html> |
Result
If user id and/or password is incorrect then it will be redirected to index.jsp page with appropriate error message.
Using correct mailid and password [email protected] and 123456