JSP PreparedStatement Example - Login -Java - Eclipse - Apache Tomcat

Java Login Example 
JSP - PreparedStatement - MySQL- Eclipse - Apache Tomcat 

Notes:

  • PreparedStatement can be used to prevent sql injection.

Project:



Project Explorer:


Source code:


LoginDao.java
package com.login.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.login.model.Login;
import com.login.utilities.DBUtilities;

public class LoginDao 
{
 public boolean checkLogin(Login login) throws SQLException
 {
  Connection con=null;
  try{
 
  con=DBUtilities.getConnection();
  
  String query="select * from sec_login where username=? and password=?";
  PreparedStatement pst= con.prepareStatement(query);
  pst.setString(1, login.getUsername());
  pst.setString(2, login.getPassword());
  ResultSet rs= pst.executeQuery();
 
  if(rs.next())
  {
   return true;
  }
  else 
  {
   return false;
  }
   
  }
  finally{
   DBUtilities.closeConnection(con);
  }
 }
 
}


DBUtilities.java
package com.login.utilities;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DBUtilities {
 
    public static Connection getConnection(){
     Connection con = null;
     
     try {
   Class.forName("com.mysql.jdbc.Driver");
   con  =DriverManager.getConnection("jdbc:mysql://localhost:3306/nn","root","nn");
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
    return con; 
     
    }
 
     public static void closeConnection(Connection con){      
      if(con!=null){
       try{
       con.close();
       }catch(SQLException e){}
      }      
     }   
       public static void closePreparedStatement(PreparedStatement ps){      
      if(ps!=null){
       try{
       ps.close();
       }catch(SQLException e){}
      }
      
     }

}



LoginManagement.java
package com.login.model;

import java.sql.SQLException;
import com.login.dao.LoginDao;

public class LoginManagement 
{

 LoginDao logindao= new LoginDao();
 public boolean checkLogin(Login login) throws SQLException
 {
  return logindao.checkLogin(login);
 }

 
}



LoginController.java
package com.login.controller;

import java.io.IOException;
import java.sql.SQLException;
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;

import com.login.model.Login;
import com.login.model.LoginManagement;

/**
 * Servlet implementation class LoginController
 */
@WebServlet("/LoginController")
public class LoginController extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginController() {
        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
  doPost(request, response);
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  
  LoginManagement loginManagement = new LoginManagement();
  RequestDispatcher rd= null;
  String action=request.getParameter("actiontype");
  if(action.equals("Login"))
  {
   
   String username=request.getParameter("username");
   String password= request.getParameter("password");
   Login login= new Login(username, password);
   boolean result=false;
   try {
     result = loginManagement.checkLogin(login);
     if(result)
     {
      request.setAttribute("user", login.getUsername());
      rd=request.getRequestDispatcher("Home.jsp");
      rd.forward(request, response);
      return;
     }
     else
     {
      request.setAttribute("err", "err");
      rd=request.getRequestDispatcher("Login.jsp");
      rd.forward(request, response);
      return;
     }
   } catch (SQLException e) {
    request.setAttribute("err", "err");
    rd=request.getRequestDispatcher("Login.jsp");  
    rd.forward(request, response);
    return;
   } 
  }
  

 }

}



Login.java
package com.login.model;

public class Login 
{

 private String username;
 private String password;
 
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public Login(String username, String password) {
  super();
  this.username = username;
  this.password = password;
 }
 
 
}



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>Log in</title>
<script type="text/javascript">
function validateForm()
{
 
 var x=document.getElementById("username");
 if (x.value=="")
   {
  
  document.getElementById('username_innermsg').innerHTML="Please enter the Username.";
    x.focus();
  return false;
   }
 
 document.getElementById('username_innermsg').innerHTML='';
 var x=document.getElementById("password");
 if (x.value=="")
   {
  
  document.getElementById('password_innermsg').innerHTML="Please enter the Password.";
    x.focus();
  return false;
   }
 
 document.getElementById('password_innermsg').innerHTML='';
}

</script>

</head>
<body>
<center>
<h1>Log in</h1>
<form action="LoginController" method="post" onsubmit="return validateForm();">
<input type="hidden" name="actiontype" value="Login">
<table >
<tr>
<td>User Name :</td><td><input type="text" name="username" id="username"></td><td width="200px"> <i style="color: red;" id="username_innermsg"></i></td>

</tr>
<tr>
<td>Password :</td><td><input type="password" name="password" id="password"></td><td width="200px"> <i style="color: red;" id="password_innermsg"></i></td>
</tr>
<tr><td></td><td  ><input type="submit" value="Login"><input type="reset" value="Cancel"></td><td ></td> </tr>
</table>


</form>
<i  style="color: red;">
<%
String er=null;
try{
 er= (String)request.getAttribute("err");
 if(er.equals("err"))
 {
  out.print("Incorrect Username/Password."); 
 }
}
catch (Exception e){
 
}

%>
</i>
</center>
</body>
</html>


Home.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>Home</title>
</head>
<body>
<%
String user =(String)request.getAttribute("user");

%>
welcome <%if(user!=null) out.print(user); %>..
<center>
<h1>You are logged in.</h1>

</center>
</body>
</html>

Download Project: SecureLoginUsingPreparedStatement

9 comments:

  1. I found a lot of interesting information here. A really good post, very thankful and hopeful that you will write many more posts like this one.

    ReplyDelete
  2. You can buy it in the US store or place the order online

    ReplyDelete
  3. Thank you for sharing above information. Keep it up. Whether you have a high or low frame rate depends on your device. You won't experience frame rate issues if your machine has a strong graphics card and processor. If you do not have any idea about what is FPS then go through this article.

    ReplyDelete
  4. I am impressed by the information that you have on this blog. Thank you for sharing. Although it is possible to replace the internal battery in a DualShock 4 controller, doing so will void your warranty and be more difficult than changing a regular battery. Read more about PS4 Controller.

    ReplyDelete
  5. I am impressed by the information that you have on this blog. Thank you for sharing. Jagex has published a number of casual games on its FunOrb website in addition to RuneScape and other games. From 2012 and 2016, American investors controlled Jagex; Chinese investors owned it from 2016 to 2020. Read this article to know about How To Use Auto Clicker in RunEscape.

    ReplyDelete
  6. Great article! Concise and informative. Thanks for sharing this valuable information. In rare cases, colorblindness can be acquired due to trauma or injury to the eye or brain. Severe head injuries, accidents, or trauma affecting the areas of the brain responsible for processing color information can result in color vision deficiencies. Go through this article to know more about Causes of colorblindness.

    ReplyDelete
  7. Hats off to the author for their skillful storytelling in such a concise format. This article was a captivating read from start to finish. To test the joystick in Windows 10, you can go to the 'Control Panel' and search for 'Game Controllers' or 'Devices and Printers'. From there, you should be able to access the properties of your joystick and perform tests to ensure it is functioning properly. Get detailed information about Test joystick in windows 10.

    ReplyDelete
  8. Recently I complete my Java programming course in Kolkata. And find some information like this. This Java login example is exactly what I needed! The step-by-step guide and the provided code make it easy to understand the process of implementing a login functionality in Java. Thanks for breaking it down and making it accessible for learners like me!

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...