Login and Register JSP MySQL Example - onlyxcodes

Tuesday, 28 May 2024

Login and Register JSP MySQL Example

In this tutorial, I will show you the steps of creating a simple login and register system using JSP and MySQL.


JavaServer Pages (JSP) is a technology that makes it possible to use Java as a programming language to create dynamic web pages. With MySQL, we can build reliable web applications.


I have used the JSP session on the login page that checks only the authenticator session login user will access the welcome page. As well as additionally I have also covered JavaScript validation both on the login and registration forms.


login and register jsp mysql example

Table Content

1. Tools Require

2. Create Database and Table

3. login page [ index.jsp ]

3.1 JavaScript validation for login form

3.2 JSP code for login form

4. registration page [ register.jsp ]

4.1 JavaScript validation for registration form

4.2 JSP code for registration form

5. welcome.jsp

6. logout.jsp

7. Run project on XAMPP server


1. Tools Require

Notepad++: – I have written all the codes in the Notepad++ editor for this.


XAMPP:– I have set up and executed this project on the XAMPP server.


Jar files:– Jsp-api.jar, servet-api.jar, and mysq-connector-java-5.1.15-bin.jar files were required for this project. Already, I've added it to the project library folder.


project directory structure of jsp login and register page set up in xampp server

2. Create Database and Table

In my PhpMyAdmin I have created "dbuser" name database and within this database, I have made the "login" table with four fields id, firstname, lastname, email, and password.


Here I put the SQL script below to generate the database and table:


CREATE DATABASE dbuser;
CREATE TABLE `login` (
  `id` int(11) NOT NULL,
  `firstname` varchar(10) NOT NULL,
  `lastname` varchar(12) NOT NULL,
  `email` varchar(40) NOT NULL,
  `password` varchar(20) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

create a login named table

To accomplish MySQL login and registration features, we now need to set up the following JSP pages.


 – index.jsp


– register.jsp


– welcome.jsp


– logout.jsp


NOTE: The session must be begun on all pages.


3. login page [ index.jsp ]

The index.jsp page is this one. Using a custom CSS code, I have made a basic login form for this page with two input boxes to collect the user's email address and password.


<form class="form-register" method="post" name="myform" onsubmit="return validate();">

    <div class="form-register-with-email">

        <div class="form-white-background">

            <div class="form-title-row">
                <h1>Login</h1>
            </div>
     
            <p style="color:red">         
            <%
            if(request.getAttribute("errorMsg")!=null)
            {
               out.println(request.getAttribute("errorMsg")); //error message for email or password 
            }
            %>
            </p>
       
            </br>

            <div class="form-row">
               <label>
                   <span>Email</span>
                   <input type="text" name="txt_email" id="email" placeholder="enter email">
               </label>
            </div>

            <div class="form-row">
               <label>
                   <span>Password</span>
                   <input type="password" name="txt_password" id="password" placeholder="enter password">
               </label>
            </div>

          <input type="submit" name="btn_login" value="Login">
                    
        </div>

        <a href="register.jsp" class="form-log-in-with-existing">You Don't have an account? <b> Register here </b></a>

   </div>

</form>
 

Login Form:


create login form using jsp

3.1 JavaScript Validation Code for Login Form

See I applied JavaScript validation for the login form to ensure all required fields are not empty.


I used the validation method onsubmit="return validate();" in the form tag.


Here, the alert method sends a special custom message with a plain modal on the header section, and the onsubmit method triggers the validate() function event and causes it at the moment of form submission.


<script>
  
 function validate()
 {
  var email = document.myform.txt_email;
  var password = document.myform.txt_password;
    
  if (email.value == null || email.value == "") //check email textbox not blank
  {
   window.alert("please enter email ?"); //alert message
   email.style.background = '#f08080';
   email.focus();
   return false;
  }
  if (password.value == null || password.value == "") //check password textbox not blank
  {
   window.alert("please enter password ?"); //alert message
   password.style.background = '#f08080'; 
   password.focus();
   return false;
  }
 }
   
</script>

3.2 JSP Code for Login Form

I have compared the user email and password fields on the login form with the database here. If it is, the session will launch and the user will be able to view the welcome page; if not, the relevant error message will appear.



<%@ page import="java.sql.*" %>  

<%
if(session.getAttribute("login")!=null) //check login session user not access or back to index.jsp page
{
 response.sendRedirect("welcome.jsp");
}
%>

<%
try
{
 Class.forName("com.mysql.jdbc.Driver"); //load driver
 
 Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dbuser","root",""); //create connection
 
 if(request.getParameter("btn_login")!=null) //check login button click event not null
 {
  String dbemail,dbpassword;
  
  String email,password;
  
  email=request.getParameter("txt_email"); //txt_email
  password=request.getParameter("txt_password"); //txt_password
  
  PreparedStatement pstmt=null; //create statement
  
  pstmt=con.prepareStatement("select * from login where email=? AND password=?"); //sql select query 
  pstmt.setString(1,email);
  pstmt.setString(2,password);
  
  ResultSet rs=pstmt.executeQuery(); //execute query and store in resultset object rs.
  
  if(rs.next())
  {
   dbemail=rs.getString("email");
   dbpassword=rs.getString("password");
   
   if(email.equals(dbemail) && password.equals(dbpassword))
   {
    session.setAttribute("login",dbemail); //session name is login and store fetchable database email address
    response.sendRedirect("welcome.jsp"); //after login success redirect to welcome.jsp page
   }
  }
  else
  {
   request.setAttribute("errorMsg","invalid email or password"); //invalid error message for email or password wrong
  }
  
  con.close(); //close connection 
 }
 
}
catch(Exception e)
{
 out.println(e);
}
%>


 

4. registration page ( register.jsp )

This is the registration page, and I've put together an easy registration form with the following four fields: password, email, last name, and first name.



<form class="form-register" method="post" onsubmit="return validate();">

    <div class="form-register-with-email">

        <div class="form-white-background">

            <div class="form-title-row">
                <h1>Register</h1>
            </div>
       
            <p style="color:green">         
            <%
            if(request.getAttribute("successMsg")!=null)
            { 
               out.println(request.getAttribute("successMsg")); //register success message
            }
            %>
           </p>
       
           </br>
       
           <div class="form-row">
               <label>
                   <span>Firstname</span>
                   <input type="text" name="txt_firstname" id="fname" placeholder="enter firstname">
               </label>
           </div>
    
           <div class="form-row">
               <label>
                   <span>Lastname</span>
                   <input type="text" name="txt_lastname" id="lname" placeholder="enter lastname">
               </label>
           </div>

           <div class="form-row">
               <label>
                   <span>Email</span>
                   <input type="text" name="txt_email" id="email" placeholder="enter email">
               </label>
           </div>

           <div class="form-row">
               <label>
                   <span>Password</span>
                   <input type="password" name="txt_password" id="password" placeholder="enter password">
               </label>
           </div>

           <input type="submit" name="btn_register" value="Register">
     
        </div>
    
        <a href="index.jsp" class="form-log-in-with-existing">Already have an account? <b> Login here </b></a>

    </div>

</form>  


Registration Form:


create registration form using jsp

4.1 JavaScript Validation Code for Registration Form

See below the custom JavaScript validation for the registration form. On this page, I have implemented the JavaScript validation format.


This JavaScript validation checks that the first and last names are written alphabetically, that the email format is correct, and that the password is between six and twelve characters long, with special characters allowed.


<script> 
 
 function validate()
 {
  var first_name= /^[a-z A-Z]+$/; //pattern allowed alphabet a-z or A-Z 
  var last_name= /^[a-z A-Z]+$/; //pattern allowed alphabet a-z or A-Z 
  var email_valid= /^[\w\d\.]+\@[a-zA-Z\.]+\.[A-Za-z]{1,4}$/; //pattern valid email validation
  var password_valid=/^[A-Z a-z 0-9 !@#$%&*()<>]{6,12}$/; //pattern password allowed A to Z, a to z, 0-9, !@#$%&*()<> charecter 
   
  var fname = document.getElementById("fname"); //textbox id fname
  var lname = document.getElementById("lname"); //textbox id lname
  var email = document.getElementById("email"); //textbox id email
  var password = document.getElementById("password"); //textbox id password
   
  if(!first_name.test(fname.value) || fname.value=='') 
  {
      alert("Enter Firstname Alphabet Only....!");
      fname.focus();
      fname.style.background = '#f08080';
      return false;                    
  }
  if(!last_name.test(lname.value) || lname.value=='') 
  {
      alert("Enter Lastname Alphabet Only....!");
      lname.focus();
      lname.style.background = '#f08080';
      return false;                    
  }
  if(!email_valid.test(email.value) || email.value=='') 
  {
      alert("Enter Valid Email....!");
      email.focus();
      email.style.background = '#f08080';
      return false;                    
  }
  if(!password_valid.test(password.value) || password.value=='') 
  {
      alert("Password Must Be 6 to 12 and allowed !@#$%&*()<> character");
      password.focus();
      password.style.background = '#f08080';
      return false;                    
  }
 }
  
</script> 
 

4.2 JSP Code for Registration Form

This code will register new user records in the database and display an appropriate message by executing the JSP code if there is no validation of the JavaScript.



<%@ page import="java.sql.*" %>  

<%
if(session.getAttribute("login")!=null) //check login session user not access or back to register.jsp page
{
 response.sendRedirect("welcome.jsp");
}
%>


<%
try
{
 Class.forName("com.mysql.jdbc.Driver"); //load driver
 
 Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dbuser","root",""); //create connection
 
 if(request.getParameter("btn_register")!=null) //check register button click event not null
 {
  String firstname,lastname,email,password;
  
  firstname=request.getParameter("txt_firstname"); //txt_firstname
  lastname=request.getParameter("txt_lastname"); //txt_lastname
  email=request.getParameter("txt_email"); //txt_email
  password=request.getParameter("txt_password"); //txt_password
  
  PreparedStatement pstmt=null; //create statement
  
  pstmt=con.prepareStatement("insert into login(firstname,lastname,email,password) values(?,?,?,?)"); //sql insert query
  pstmt.setString(1,firstname);
  pstmt.setString(2,lastname);
  pstmt.setString(3,email);
  pstmt.setString(4,password);
  
  pstmt.executeUpdate(); //execute query
  
  request.setAttribute("successMsg","Register Successfully...! Please login"); //register success messeage

  con.close(); //close connection
 }
}
catch(Exception e)
{
 out.println(e);
}
%> 
 

5. welcome.jsp

This page welcomes you. This page displays a login email address that appears when the user successfully logs in.


The "logout.jsp" page hyperlink is provided by this page. Users who click this link will be taken to the "index.jsp" page and forced to log out.


<div class="main-content">
 
 <center>
 
 <%
 if(session.getAttribute("login")==null || session.getAttribute("login")==" ") //check condition unauthorize user not direct access welcome.jsp page
 {
   response.sendRedirect("index.jsp"); 
 }
 %>
 
 <h1> Welcome, <%=session.getAttribute("login")%> </h1>

 <h2><a href="logout.jsp">Logout</a></h2>
    
 </center>
  
</div>
 

create login page in jsp with mysql and session

6. logout.jsp

Just two lines of JSP code on this page employ the session.invaidate() method to end the active authorized user session. The page will delete the session and go straight to the 'login/index' page.



<% 
session.invalidate(); //destroy session
response.sendRedirect("index.jsp");
%>
 

7. Run Poject in XAMPP Server

Launch the XAMPP server, then select Apache, MySQL, and Tomcat once the whole service has started.


Open your preferred web browser and type this URL http://localhost:8080/login-register-jsp/ and test this web project.


start to Apache, MySQL and Tomcat service in XAMPP server

Learn More:

Insert Update Delete using JSP and MySQL

How to Display Data from Database in Modal

How to call Java Class from JSP Page in Eclipse

Json Encode In JSP - MySQL Data Encode In Json Example

Role Based Access Control in Java Web Application Example


Download Codes

3 comments:

Post Bottom Ad