Login and Register Using JSP & MySQL - onlyxcodes

Wednesday, 17 January 2018

Login and Register Using JSP & MySQL

In this tutorial, we will learn how to create a login and register page using JSP and MySQL in a practical conceptual way. Registration and login system is typical to web application or project of any kind. And session plays an important role in this type of application, so we need to use the session for that.

In this tutorial, we use the JSP session in the login page because only the authenticator session login user can access the personalized welcome page. And it is necessary to check whether unauthenticated user access personalizes the page when invalid email and password message cause. As well as Additionally I have covered JavaScript validation both on the login and registration form. 

Login and Register Using JSP & MySQL

Table Content

1. Requirement

2. Database and Table Design

3. index.jsp [ login page ]

    3.1 custom JavaScript validation for login form

    3.2 JSP code for login form

4. register.jsp [ registration page ]

    4.1 custom JavaScript validation for register form

    4.2 JSP code for register form

5. welcome.jsp

6. logout.jsp

7. Run project on XAMPP server


1. Requirement

Notepad++: – Download  I've written all the codes in Notepad++ editor for this project.

XAMPP:– Download  I've set up and execute this project on the XAMPP server.

Jar files:– This project needed jsp-api.jar, servet-api.jar and mysq-connector-java-5.1.15-bin.jar files. I've already included in the project lib folder go to the bottom section and download all available jar project zip file.

the project directory structure of JSP login and register page set up in XAMPP server

2. Database and Table Design

Create a database and table first, as below. To generate a database and table, copy-paste the SQL code below into PHPMyAdmin.

Database: dbuser

Table: login

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

Now we need to establish the following JSP pages to perform MySQL login and register functionality.

 – index.jsp

 register.jsp

 welcome.jsp

– logout.jsp

NOTE: The session must be begun on all pages.

3. index.jsp [ login page ]

Create a simple login form using a custom CSS plugin on this page. And take two input boxes that will take user-entered email 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>
 

Go to the tutorial end and download the custom CSS template code from the project zip file.

JSP login form

3.1 Custom JavaScript Validation Code for Login Form

See JavaScript validation for the login form to ensure all required fields are filled in. The onsubmit method activates the validate() function event and causes it at the time of submission of the form. And the alert method sends a unique custom message with plain modal on the header section.

<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

Below JSP code compares the combination of user email and password in the database, and when both results are contained in the table. If found, a session will start and allow the user to access the welcome page, otherwise, the appropriate message will be displayed.


<%@ 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);
}
%>


 

Learn more :

4. register.jsp [ registration page ]

This page contains a simple HTML form with the firstname, lastname, email, and password all necessary registration fields. This form is the same as the form of the style login, but two additional fields are included with little improvements.


<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>  



See below again the stylish registration template created by custom CSS codes goes to the end of the tutorial and all codes are available for downloading a project zip file.

JSP registration form

4.1 Custom JavaScript Validation Code for Register Form

See below custom JavaScript validation for the registration form. On this page, the JavaScript offers a ready-made format that I have to implement. And below the whole validation check first name & last name must be typed alphabetically, valid email format, password length 6 to 12 with special character permitted.

<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 [email protected]#$%&*()<>]{6,12}$/; //pattern password allowed A to Z, a to z, 0-9, [email protected]#$%&*()<> 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 [email protected]#$%&*()<> character");
      password.focus();
      password.style.background = '#f08080';
      return false;                    
  }
 }
  
</script> 
 

4.2 JSP Code for Register Form

If no validation of JavaScript occurred then new user records registering in a database with an appropriate message by following JSP code.


<%@ 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 displays the user authenticate welcome message with an email address. And provide users clicking on that hyperlink and then redirecting to the 'logout.jsp ' page.

<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>
 

JSP welcome page

6. logout.jsp

This page contains only two lines of JSP code to use session.invaidate() method to destroy the current authenticated user session. The page will immediately move to the 'login/index' page after destroying the session.


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

7. Run Project in XAMPP Server

Start the XAMPP server and click on Apache, MySQL, and Tomcat after start whole services.

start to Apache, MySQL and Tomcat service in XAMPP server

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

Happy coding :)

Download Codes

1 comment: