Login using JSP, Servlet and MYSQL using Eclipse

How to create a login using JSP, Servlet, and MYSQL. Continue Java web application development tutorial let’s see how to add login form in JSP or how to add login in your Java web project.

As you know this is tutorial series So all the Java web development tutorials are related to each other. We are using some common code from the previous tutorial  So I will recommend you to check the previous tutorial.

Login with JSP, Servlet and MYSQL

  • Design Login form in JSP.
  • Create a login method in UserModel.
  • Handle the login request in LoginController.

Desing login form in JSP

login.jsp

<%@page import="com.javawebapp.utility.ServletUtility"%>
<body>
  <%@ include file="header.jsp"%>
  <main class="login-form">
  <div class="cotainer">
    <div class="row justify-content-center">
      <div class="col-md-8">
        <div class="card">
          <div class="card-header">
            Login 
            <h6 style="color: red;"><%= ServletUtility.getErrorMessage(request) %></h6>
            <h6 style="color: green;"></h6>
          </div>

          <div class="card-body">

            <form action="" method="post">

              <div class="form-group row">
                <label for="email_address" 
                  class="col-md-4 col-form-label text-md-right">Login Id<font color="red">*</font></label>
                <div class="col-md-6">
                  <input type="text" id="login"  class="form-control" placeholder="Enter Login Id"
                    name="login" value="" >
                    <font  color="red"></font>
                </div>
              </div>

              <div class="form-group row">
                <label for="password"
                  class="col-md-4 col-form-label text-md-right">Password<font color="red">*</font></label>
                <div class="col-md-6">
                  <input type="password" id="password" class="form-control" placeholder="Enter Password"
                    name="password" value="" >
                    <font color="red"> </font>
                </div>
              </div>



              <div class="col-md-6 offset-md-4">
                <input type="submit" class="btn btn-primary" name="operation" value="Login">
                <a href="" class="btn btn-link"> Forgot Your Password? </a>
              </div>
            </form>
          </div>

        </div>
      </div>
    </div>
  </div>
  </main>
  <div style="margin-top: 170px">
    <%@ include file="footer.jsp"%>
  </div>

Add login method in UserModel.java

This UserLogin(String login, String password ) will help to perform the login activity.  Please check the User registration with JSP, Servlet, and MYSQL to get the complete code of UserModel.java

//Login User......
  public static UserBeans  UserLogin(String login,String password) {
    Connection con;
    UserBeans user = null;
    try {
      con = JDBCDataSource.getConnection();
      PreparedStatement stmt = con.prepareStatement("Select * from user where login=? and password = ?");
      stmt.setString(1,login);
      stmt.setString(2,password);
      ResultSet rs = stmt.executeQuery();
      if(rs.next()) {
        user = new UserBeans();
        System.out.println("ID: "+rs.getLong("id"));
        user.setId(rs.getLong("id"));
        user.setFirstName(rs.getString("fname"));
        user.setLastName(rs.getString("lname"));
        user.setLogin(rs.getString("login"));
        user.setPassword(rs.getString("password"));
        user.setDob(rs.getDate("dob"));
        user.setMobileNo(rs.getString("mobile"));	
      }
      
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
    return user;
  }

Create a servlet(Login Controller)

LoginCTL.java

package com.javawebapp.Controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.javawebapp.beans.UserBeans;
import com.javawebapp.model.UserModel;
import com.javawebapp.utility.ServletUtility;

/**
 * Servlet implementation class LoginCTL
 */
@WebServlet(name= "LoginCTL", urlPatterns = {"LoginCTL"})
public class LoginCTL extends HttpServlet {
  private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginCTL() {
        super();
        // TODO Auto-generated constructor stub
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    ServletUtility.forward("jsp/login.jsp", request, response);
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
       UserBeans user = new UserBeans();
       String login=request.getParameter("login");
       String pwd=request.getParameter("password");
       
       user = UserModel.UserLogin(login,pwd);
       if(user != null) {
      	 //ServletUtility.setSuccessMessage(request.getParameter("login")+ " is login successfully", request);
      	 ServletUtility.redirect("jsp/welcome.jsp", request, response);
       }else {
      	 ServletUtility.setErrorMessage("Invalid User", request);
      	 ServletUtility.forward("jsp/login.jsp", request, response);
       }
  }

}

welcome.jsp

Create a welcome JSP page to redirect the user if the login is successful.

<%@page import="com.javawebapp.utility.ServletUtility"%>
<body>
<%@ include file="header.jsp"%>
<h3 style="color: green;"><%=ServletUtility.getSuccessMessage(request)%></h3>
<h1>Welcome User</h1>
<%@ include file="footer.jsp"%>
</body>
</html>