Java

A Login Application using JSP, Servlet, and JDBC

Programmingempire

The following example shows A Login Application using JSP, Servlet, and JDBC. Specifically, the Login.jsp file creates a client-side form that allows users to enter their credentials. Once, the user enters data and clicks on the Submit button, the LoginServlet executes.

Furthermore, the database table used here is named myusers. The following figure shows the data stored in this table.

The Database Table - myusers
The Database Table – myusers

Login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Form</title>
</head>
<body>
   <center><h1>Login Form</h1></center>
   <form name="f1" method="post" action="LoginServlet">
   <center><table>
      <tr>
         <td>User ID: </td>
         <td><input type="text" name="t1"/></td>
      </tr>
        <tr>
         <td>Password: </td>
         <td><input type="password" name="t2"/></td>
      </tr>
        <tr>
         <td>User Type: </td>
         <td><input type="text" name="t3"/></td>
      </tr>
     <tr>
         
         <td colspan="2" style="text-align: center;"><input type="submit" value="Submit"/></td>
      </tr>  
   </table></center>
   </form>
</body>
</html>

LoginServlet.java

Since the method attribute in the form has a value post, the doPost() method of the servlet executes. As can be seen, the doPost() method starts with a call to setContentType() method of the response object. Also, an object of the PrintWriter is created to create output that will be sent to the client. After that, the data entered by the user is retrieved using the getParameter() method.

In addition, a try-catch block is defined to perform the database access operation. In short, the request parameter values are compared with values retrieved from the database table in each iteration. Once, a match is found, the servlet displays the Welcome message to the user. Likewise, in case, the user’s credentials don’t match, the servlet calls the sendRedirect() method. Furthermore, the path of the JSP file containing the Login Form is specified as a parameter. Hence, the user is presented with the original JSP page in case, the login credentials do not match.

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

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("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public LoginServlet() {
        super();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         response.setContentType("text/html");
         java.io.PrintWriter ob=response.getWriter();
         ob.println("<html><head><title>Home Page</title></head>");
         ob.println("<body>");
         String userid, password, usertype;
         int found=0;
         userid=request.getParameter("t1");
         password=request.getParameter("t2");
         usertype=request.getParameter("t3");
         
         
         try{
            Class.forName("com.mysql.jdbc.Driver");
     	    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/d1", "root", "123456");
            System.out.println(con);
            Statement stmt=con.createStatement();  
     		ResultSet myrows=stmt.executeQuery("select * from myusers");  
     		while(myrows.next())
       	    {
     			
     			String x=myrows.getString(1);
     			String y=myrows.getString(2);
     			String z=myrows.getString(3);

     			if((userid.equals(x)) && (password.equals(y)) && (usertype.equals(z))){
     				ob.println("Login Successful");
     				ob.println("<center><h1>Welcome " + userid+"</h1></center>");
     				found=1;
     				break;
     			}
       	    }
     		if(found==0)
     		{
     			response.sendRedirect(request.getContextPath() + "/Login.jsp");
     		}
         }catch(Exception ex)
         {
        	 ex.printStackTrace();
         }
           ob.println("</body></html>");
	}
}

Output

Login Form Displayed to Client
Login Form Displayed to Client
Example of A Login Application using JSP, Servlet, and JDBC
Example of A Login Application using JSP, Servlet, and JDBC

Further Reading

programmingempire

You may also like...