Follow

Welcome to TechYari!

Tutorials on webdesign, web development and more...

Login, Registration In J2EE using jQueryUI tabs and MySql Database



By  Vipin Dubey     4/17/2014    Labels:,,,,,,, 

Introduction 

In this tutorial we are going to look at a typical login and registration example using the ever popular jquery ui tabs in place with J2EE. We will be using MVC model for the tutorial, this is not based on any MVC framework so we will create our own forced MVC model using different packages, servlets and class files. MySql database will serve as a back end for registering and authenticating users.

jquery-tabs-login-registration-demo

You can download the source code using the link below as a war file and import it directly to Eclipse. You will only need the database and a table ready to use which can be built using the script provided below.

Download Source

Project Setup

I will be using Elcipse for J2EE with MySql database and Apache Tomcat 7. This example will require one additional jar called mysql-connector for jdbc. Below is a screenshot of completed project on Eclipse.

project-structure

Creating the Users table

We need a table to store users for our site. We will be creating a table called users with 6 fields. Refer below query to create the table.


   CREATE TABLE users(
    id INT AUTO_INCREMENT,
    fullname VARCHAR (50),
    email VARCHAR (50),
    password VARCHAR (50),
    gender VARCHAR (50),
    birthdate VARCHAR (50),
    PRIMARY KEY ( id )
    ) 

We do not need any data to be populated as we will user registration page for the same.


Creating the login and registration form using jQuery UI tabs

We will require a JSP instead of plain html as we need to show few errors based on username/password authentication. This page will be created in WebContent folder and our web.xml file will use this as welcome page for website. I have not used any front end and back end validation as it will make the tutorial very large.  
If you require one you can use JavaScript/jQuery validation plugin and regular Expressions on the Java Classes to do the validations.
Just copy and paste this code in a file named index.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login and registartion example in J2EE</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="style.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(function() {
  $( "#tabs" ).tabs();
});
</script>
</head>
<body>
 <div class="wrapper">
 <div class="header">
  <h1>Tabbed Login and Registration example with jQuery UI in J2EE using MySql database</h1>
 </div>
 
 <div class="container">
  <div class="instruction">
<div id="tabs">
  <ul>
    <li><a href="#login">Login</a></li>
    <li><a href="#register">Register</a></li>
  </ul>
  <div id="login">
   <% 
   if("Invalid username or password".equalsIgnoreCase((String)session.getAttribute("error"))){ %>
    <h6> Invalid user name or password. Please try again.</h6>
   <%} %>
    <form method="post" action="LoginController">
     <label for="email">Email:</label>
     <input type="text" name="email" id="email" class="email" placeholder="Your email address"/>
     <label for="password">Password:</label>
     <input type="password" name="password" id="password" class="password" placeholder="Your password"/>
     <input type="submit" value="Login">
    </form>
  </div>
  <div id="register">
   <form method="post" action="RegistrationController">
    <label for="fullname">Full Name:</label><br/>
     <input type="text" name="fullname" id="fullname" class="fullname" placeholder="Your full name"/>
     <br/>
     <label for="email">Email:</label><br/>
     <input type="text" name="email" id="email" class="email" placeholder="Your email address"/>
     <br/>
     <label for="password">Password:</label><br/>
     <input type="password" name="password" id="password" class="password" placeholder="Your password"/>
     <br/>
     <label for="gender">Gender:</label><br/>
     <select name="gender" id="gender" class="gender">
      <option value="Male">Male</option>
      <option value="Male">Female</option>
     </select>
     <br/>
     <label for="birthdate">Birth Date:</label><br/>
     <input type="text" name="birthdate" id="birthdate" class="birthdate" placeholder="Your birth date"/>
     <br/>
     <input type="submit" value="Register">
   </form>
  </div>
</div>
  </div>
 </div>
 
 <div class="footer">
  &copy; 2014 <a href="http://techyari.in">TechYari</a> All rights reserved. 
 </div>
 </div>
</body>
</html>

Styling the Login & Registration page

Create a file called style.css and add following styles to it.


body{
 background-color: #e6e6e6;
 font-family: Helvetica;
 font-size: 17px;
 color: #666;
 margin: 0px;
 padding: 0px;
}
.wrapper{ 
  width:1024px;
     margin: 0 auto;
     background:white;
     }
     
.header{padding:10px;background-color:#4D82CA;color:white}     

h1{
 text-align:center;
 font-size:20px;
 margin:0px;
}

.container{
 min-height:400px;
 border-top: 1px solid gray;
 padding: 50px;
 }
.center{margin-left:43%}

.footer{ text-align:center;border-top: 1px solid gray;padding:10px;background-color:#4D82CA;color:white }

.footer a {color:lavender;text-decoration:none;}


Creating the Packages, Servlets and Java Classes

As we intend to organize this example as an MVC application we will create three packages insider our src folder
  1. in.techyari.example.dao
  2. in.techyari.example.controller
  3. in.techyari.example.model
  • dao package will contain classes related to Database Connection and Data Access Objects for our Model Class.
  • controller package will contain the servlets for Login and Registration form
  • Model will contain our User model class having 6 attributes.
Create a class named Database inside in.techyari.example.dao use below code for reference, modify the database name, username and password according to your database. 

package in.techyari.example.dao;

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

public class Database {
 
 
 public Connection getConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
  
  Connection connection =  null;
  
  // Store the database URL in a string
  String url = "jdbc:mysql://localhost:3306/tutorials"; 
  
  Class.forName("com.mysql.jdbc.Driver").newInstance();
  
  // set the url, username and password for the databse 
  connection = DriverManager.getConnection(url,"root","");   
  return connection;
  
 }
}

Now we will create our Model class User which will go inside in.techyari.example.model, here we are going to provide two constructors, first the default one and second with 5 arguments to create a User object when someone registers on our site. We will also override toString method so that we can print some useful info for our class in console during development and debugging.


package in.techyari.example.model;

public class User {
 
 private int id;
 private String fullname;
 private String email;
 private String password;
 private String gender;
 private String birthdate;
 
 public User(){
  
 }
 
 public User(String fullname, String email, String password,String gender, String birthdate) {
  this.fullname = fullname;
  this.email = email;
  this.password = password;
  this.gender = gender;
  this.birthdate = birthdate;
 }
 
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getFullname() {
  return fullname;
 }
 public void setFullname(String fullname) {
  this.fullname = fullname;
 }
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public String getGender() {
  return gender;
 }
 public void setGender(String gender) {
  this.gender = gender;
 }
 public String getBirthdate() {
  return birthdate;
 }
 public void setBirthdate(String birthdate) {
  this.birthdate = birthdate;
 }

 @Override
 public String toString() {
  return "User [id=" + id + ", fullname=" + fullname + ", email=" + email
    + ", gender=" + gender + ", birthdate=" + birthdate + "]";
 }
 
 
 
}

Creating the UserDAO class to insert and validate users. We will first create a UserDAO interface and then we will implement this interface in UserDAOImpl class. both will reside in in.techyari.example.dao package.

Below is the code for UserDAO Interface



package in.techyari.example.dao;

import in.techyari.example.model.User;

public interface UserDAO {
 
 public User getUserByEmail(String email,String password);
 public int createOrUpdateUser(User u);
 
}

Now the UserDAOImpl class which will provide the actual implementation for methods in UserDAO

package in.techyari.example.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import in.techyari.example.model.User;

public class UserDAOImpl implements UserDAO{
 
 Database db = new Database();
 

 @Override
 public User getUserByEmail(String email, String password) {
  User user = new User();
  try {
   Connection connection = db.getConnection();
   PreparedStatement ps = connection.prepareStatement("SELECT * FROM users WHERE email LIKE ? AND password LIKE ?");
   ps.setString(1, email);
   ps.setString(2, password);
   ResultSet rs = ps.executeQuery();
   while(rs.next()){
    user.setId(rs.getInt("id"));
    user.setFullname(rs.getString("fullname"));
    user.setEmail(rs.getString("email"));
    user.setGender(rs.getString("gender"));
    user.setBirthdate(rs.getString("birthdate"));
   }
   
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 
  return user;
 }

 @Override
 public int createOrUpdateUser(User u) {
  int result = 0;
  try {
   Connection connection = db.getConnection();
   PreparedStatement ps = connection.prepareStatement("INSERT INTO users (fullname,email,password,gender,birthdate) VALUES (?,?,?,?,?)");
   ps.setString(1, u.getFullname());
   ps.setString(2, u.getEmail());
   ps.setString(3, u.getPassword());
   ps.setString(4, u.getGender());
   ps.setString(5, u.getBirthdate());
   result = ps.executeUpdate();
   
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return result; 
  
 }

}

So by far we have created our model and database access objects with a database class to provide the jdbc connectivity between our java and mysql. Now we will create our controllers, we have two major actions in this application :

  • Login
  • Registration
Creating the Registration Controller : create a servlet named RegistrationController and place inside in.techyari.example.controller package. This servlet uses annotations to provide us servlet configuration for the path RegistrationController which is being used as action by "registration form" in index.jsp page. So upon hitting the submit button you will call this controller which will further take care of registering the user on our database.


package in.techyari.example.controller;

import in.techyari.example.dao.UserDAOImpl;
import in.techyari.example.model.User;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class RegistrationController
 */
@WebServlet("/RegistrationController")
public class RegistrationController extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegistrationController() {
        super();
        // TODO Auto-generated constructor stub
    }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  
  String fullname = request.getParameter("fullname");
  String email = request.getParameter("email");
  String password= request.getParameter("password");
  String gender = request.getParameter("gender");
  String birthdate = request.getParameter("birthdate");
  
  User user = new User(fullname,email,password,gender,birthdate);
  
  UserDAOImpl userDAOImpl = new UserDAOImpl();
  
  int result = userDAOImpl.createOrUpdateUser(user);
  
  if(result == 0){
   
   System.out.println("User could not be registered");
  }else{
   
   System.out.println(user.getFullname()+" You have been registered successfully");
   response.sendRedirect("success.html");
  }
  
 }

}

You might have noticed that registration controller redirects to a success page when a user is successfully registered. Below is the code for success.html (I am using html page here as I don't need to perform any logical/dynamic operations)


<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login and registartion example in J2EE</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="style.css">

</head>
<body>
 <div class="wrapper">
 <div class="header">
  <h1>Tabbed Login and Registration example with jQuery validation in J2EE using MySql database</h1>
 </div>
 
 <div class="container">
  <div class="instruction">
   <h3> You have been successfully registered.<a href="index.jsp">Click here to back to login page</a></h3>
  </div>
 </div>
 
 <div class="footer">
  &copy; 2014 <a href="http://techyari.in">TechYari</a> All rights reserved. 
 </div>
 </div>
</body>
</html>

Ok so we now have registration in place, time to login, use the same convention and create a servlet named LoginController in same package. Below is the code for LoginController


package in.techyari.example.controller;

import in.techyari.example.dao.UserDAOImpl;
import in.techyari.example.model.User;

import java.io.IOException;

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 javax.servlet.http.HttpSession;

/**
 * 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#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
 
  String error;
  String email = request.getParameter("email");
  String password= request.getParameter("password");
  HttpSession session = request.getSession();
  UserDAOImpl userDAOImpl = new UserDAOImpl();
    
  User user = userDAOImpl.getUserByEmail(email,password);
  
  
  if(user.getFullname() == null){
   error = "Invalid username or password";
   System.out.println("Could not log you in please check your email & password");
   session.setAttribute("error", error);
   response.sendRedirect("index.jsp");
  }else{
   session.setAttribute("user",user);
   System.out.println(session.getAttribute("user"));
   error = "none";
   response.sendRedirect("welcome.jsp");
  }
 }

 @Override
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  // TODO Auto-generated method stub
  if("logout".equalsIgnoreCase(request.getParameter("query"))){
   
      HttpSession session = request.getSession();
      session.removeAttribute("user");
      session.invalidate();
      response.sendRedirect("index.jsp");
   }
 }

}

We have everything in place now, we just need the user to redirect to welcome.jsp page based on conditions calculated by LoginController. So create a welcome.jsp page in WebContent folder and you are done. Refer below for the code.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"
  import = "in.techyari.example.model.User"   
    
 %>
<!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 and registartion example in J2EE</title>
</head>
<body>
 <%
   User user = (User)session.getAttribute("user");
   if(user!=null){ %>
  
      <h3>Welcome <% out.print(user.getFullname()); %></h3>
      <a href="LoginController?query=logout">Logout</a>
      
      <% }else{ %> 
       <h3>Your don't have permission to access this page</h3>
      <% } %>
 
 
</body>
</html>

Download Source

Now deploy this app to Tomcat and you have a web app ready with registration and login all placed at work. The idea behind this tutorial was to give exposure to MVC design pattern and using it with real world. This is not a perfect piece of code as it does not use encryption for password, client side & server side validation and few other required pieces like form auto fill on registration error. I will be creating a separate tutorial for them as they themselves are huge topics and placing them here would make this tutorial very lenthy.

Kindly share this tutorial if you find it useful. Share your concerns/queries using the comment box below.

About Vipin Dubey

A web developer, blogger, amateur designer and an open source enthusiast.

No comments:

Post a Comment


Contact Form

Name

Email *

Message *

Labels

Follow TechYari on

Translate

About TechYari

Tech Yari is a Technical Blog featuring articles on Web Development, Web Design, Search Engine Optimization, Social Media Marketting and Programming.