How to create login system using jsp and servlet with mysql database

How To Create Login System Uisng JSP And Servlet With MySql DataBase

Hello Java Lovers, In this tutorial we are going to create alogin system using JSP and SERVLET technology with MySql Database.

Structure :
















Now before proceeding further create a database with any name and a table with any name and insert some values like Email as  amira@gmail.com and Password as amira123.

Now open eclipse IDE and follow the steps :

Create a dynamic web project in eclipse and add the server without fail.

Now create a login form  as 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</title>
<style type="text/css">
#btn{
background-color: dodgerblue;
}
#errMsg{
color:red;
}
</style>
</head>
<body><br/><br/><br/>
<%
String email_errorMsg="";
String password_errorMsg="";
if(request.getAttribute("email_errorMsg") !=null){
     email_errorMsg=(String)request.getAttribute("email_errorMsg");
}
if(request.getAttribute("password_errorMsg") !=null){
     password_errorMsg=(String)request.getAttribute("password_errorMsg");
}
%>
<center>
<form action="LoginController" method="POST">
Email :<input type="text" name="Email"><br/>
<b id="errMsg"><%=email_errorMsg %></b>
<br/>
Password :<input type="text" name="Password"><br/>
<b id="errMsg"><%=password_errorMsg %></b>
<br/>
<input type="submit" value="Login" id="btn"/>
</form>
</center>
</body>
</html>

Now create package com.MySql_DBConnection and in this package create a class DBConnection.java
package com.MySql_DBConnection;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnection {
private static Connection conn=null;
public static Connection getDbConnection() {
     try {
           Class.forName("com.mysql.jdbc.Driver");
          conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/FOr_Amira", "root", "");
     } catch (Exception e) {
           System.out.println("Can Not Connect To DataBase");
     }
     return conn;
}
}

Now create a package com.AuthenticateUsers and create a class AuthenticateUser.java
package com.AuthenticateUsers;
import java.sql.Connection;
import com.MySql_DBConnection.DBConnection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AuthenticateUser {
private static Connection conn;
public static String authenticateUser(String username,String password) {
     String msg="";
     String query;
     conn=DBConnection.getDbConnection();
     query="SELECT Password FROM login WHERE Email=?";
     try {
           PreparedStatement pst=conn.prepareStatement(query);
           pst.setString(1, username);
           ResultSet rs=pst.executeQuery();
           if(rs.next()) {
                if(rs.getString(1).equalsIgnoreCase(password)) {
                     msg="Success";
                }
                else {
                     msg="Invalid Password";
                }
           }
           else {
                msg="Invalid Email";
           }
     } catch (SQLException e) {
           System.out.println("Can Not Coonect To DB");
     }
     return msg;
}
}

Now create a package com.Controller_Servlet and create a servlet LoginController.java
package com.Controller_Servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.AuthenticateUsers.AuthenticateUser;
public class LoginController extends HttpServlet {
     private static final long serialVersionUID = 1L;
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        HttpSession session=request.getSession();
        String Email=request.getParameter("Email");
        String Password=request.getParameter("Password");
       
        String msg=AuthenticateUser.authenticateUser(Email, Password);
        if(msg.equalsIgnoreCase("Success")) {
           session.setAttribute("Email",Email);
           request.getRequestDispatcher("loginSuccess.jsp").forward(request, response);
        }
        else if(msg.equalsIgnoreCase("Invalid Email")){
          request.setAttribute("email_errorMsg",msg);
          request.getRequestDispatcher("login.jsp").forward(request, response);
        }
        else if(msg.equalsIgnoreCase("Invalid Password")){
           request.setAttribute("password_errorMsg",msg);
            request.getRequestDispatcher("login.jsp").forward(request, response);
       } 
     }
}

Now create a loginSuccess.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">
<%
if(session.getAttribute("Email") == null){
     response.sendRedirect("login.jsp");
}
%>
<title><%=session.getAttribute("Email") %></title>
</head>
<body><br/><br/>

<center>
Welcome : <%=session.getAttribute("Email") %><br/><br/>

<form action="Logout" method="POST">
<input type="submit" value="Logout?">
</form>
</center>

</body>
</html>

Now create Logout.java servlet in com.Controller_Servlet package
package com.Controller_Servlet;

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

public class Logout extends HttpServlet {
     private static final long serialVersionUID = 1L;

     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           response.setContentType("text/html");
           HttpSession session=request.getSession();
         session.invalidate();
         response.sendRedirect("login.jsp");
     }
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>For_Amira</display-name>
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>LoginController</display-name>
    <servlet-name>LoginController</servlet-name>
    <servlet-class>com.Controller_Servlet.LoginController</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginController</servlet-name>
    <url-pattern>/LoginController</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>Logout</display-name>
    <servlet-name>Logout</servlet-name>
    <servlet-class>com.Controller_Servlet.Logout</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Logout</servlet-name>
    <url-pattern>/Logout</url-pattern>
  </servlet-mapping>
</web-app>

Now run your project on server, if everything goes right then a login form will appear. Enter Email and Password and observe the outputs. If you have any query use comment box.

No comments

You May Like Also

Programming Knowledge


Java JDK
Reversing String in Java
Java Generic Concept With Simple Example
Java Generic Objects Behavior In Non-Generic Area
Creating Connection With MySql Databse Using Java Application
Performing Database Operations Java MySql Insert Update Delete Select
Java Inserting Data in MySql Databse Table
Java Basic Login System Using MySql Database Table
JSP Login System Using MySql Databse
Jsp Servlet Login And Logout System Using Mysql Database Table
What is jdk in Java?
Exaplain inheritance in Java with example?
Exaplain polymorphism in Java with example?
Exaplain abstraction in Java with example?
Exaplain encapsulation in Java with example?
What is the use of this keyword in Java?
Explain ArrayList With Example
Explain LinkedList With Example
Explain Vector Class With Example
Explain Vector Class With Example
Generics in java with example
Behavior of generic objects
How can i pass generic class to a method in java
How to create a login system in jsp using mysql database?
How to create a login and logout system in jsp & servlet using mysql database?
How to connection a simple Java application with mysql database?
How to insert values in mysql databse usiong Java applications?
Perform insertion, retrieval, updatation and delete operations?
How to create a simple login system in java using mysql database?

PHP Login System Using MySql Database
PHP Complete Login System With Session And Logout Using MySql Database