Pages Navigation Menu

Coding is much easier than you think

Tab Style Login and Signup example using jQuery in Java web application

 
Tab Style Login Signup using jQueryin Java
 
In this post, I am going to describe on how to design tab style login and registration panel using jquery ui tabs in java web applications. Here I’m using oracle database as a back end for registering and authenticating users.
 
Libraries required for the setup,

  • Servlet-api.jar
  • jQuery
  • jQuery UI
  • Ojdbc.jar
  •  
    Now create a dynamic web project in eclipse and create two folders under WebContent and name it as ‘js’ and ‘css’. And add the downloaded jQuery javascript and css files to it. The final project structure will be as shown below
     
    Login & sign up in java
     
    Now create a user table in Oracle database using the query below.

    CREATE TABLE users (name VARCHAR (50), email VARCHAR (50), password VARCHAR (50), gender VARCHAR (50))
     

    Jsp page

     

    <!DOCTYPE html>
    <html>
    <head>
    <title>Login and registration</title>
    <link rel="stylesheet" href="css/jquery-ui.css">
    <link rel="stylesheet" href="css/style.css">
    <script src="js/jquery-1.11.1.js"></script>
    <script src="js/jquery-ui.js"></script>
    <script>
    $(function() {
      $( "#tabs" ).tabs();
    });
    </script>
    </head>
    <body>
    <div class="wrapper">	
    <div class="container">
    <div id="tabs">
      <ul>
        <li><a href="#login">Login</a></li>
        <li><a href="#register">Sign up</a></li>
      </ul>
      <div id="login">
      	<% 
      	if("Invalid Email or password".equals((String)session.getAttribute("error"))){ %>
      		<h6> Invalid Email or password. Please try again.</h6>
      	<%} %>
        <form method="post" action="LoginController">
        	<label for="email">Email:</label>
        	<br/>
        	<input type="text" name="email" id="email"/>
        	<br/>
        	<label for="password">Password:</label>
        	<br/>
        	<input type="password" name="password" id="password"  />
        	<br/>
        	<br/>
        	<input type="submit" value="Login">
        </form>
      </div>
      <div id="register">
      	<form method="post" action="RegistrationController">
      		<label for="fullname">Name:</label><br/>
        	<input type="text" name="fullname" id="fullname" />
        	<br/>
        	<label for="email">Email:</label><br/>
        	<input type="text" name="email" id="email" />
        	<br/>
        	<label for="password">Password:</label><br/>
        	<input type="password" name="password" id="password" />
        	<br/>
        	<label for="gender">Gender:</label><br/>
        	<select name="gender" id="gender">
        		<option value="Male">Male</option>
        		<option value="Female">Female</option>
        	</select>
        	<br/>
        	<br/>
        	<input type="submit" value="Register">
      	</form>
      </div>
    </div>
    </div>
    </div>
    </body>
    </html>
    

     

    User defined CSS

     

    body {
    	background-color: #e6e6e6;
    	font-family: Helvetica;
    	font-size: 17px;
    	color: #666;
    	margin: 0px;
    	padding: 0px;
    }
    
    .wrapper {
    	width: 1024px;
    	height: 650px;
    	margin: 0 auto;
    	background: white;
    	margin: 0 auto;
    }
    
    .container {
    	min-height: 400px;
    	border-top: 1px solid gray;
    	padding: 50px;
    }
    

     

    Recommended reading :

  • Auto complete in java web application using JQuery
  • AJAX implementation in java web application using JQuery
  • AJAX implementation in java web application using JQuery and JSON
  •  

    Controller

    File: LoginController.java

    LoginController doPost method gets triggered on clicking Login button and its doGet Method gets triggered on clicking logout

     

    package com.controller;
    
    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;
    
    import com.dao.UserDAO;
    
    public class LoginController extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	protected void doPost(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    
    		String error;
    		String email = request.getParameter("email");
    		String password = request.getParameter("password");
    		HttpSession session = request.getSession();
    		UserDAO userDAO = new UserDAO();
    
    		String userName = userDAO.verifyUser(email, password);
    
    		if (userName == null) {
    			error = "Invalid Email or password";
    			session.setAttribute("error", error);
    			response.sendRedirect("index.jsp");
    		} else {
    			session.setAttribute("user", userName);
    			response.sendRedirect("welcome.jsp");
    		}
    	}
    
    	@Override
    	protected void doGet(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		if ("logout".equalsIgnoreCase(request.getParameter("param"))) {
    			HttpSession session = request.getSession();
    			session.removeAttribute("user");
    			session.invalidate();
    			response.sendRedirect("index.jsp");
    		}
    	}
    }
    

     
    SignupController

    This controller gets triggred on clicking Register button under Signup tab
     

    package com.controller;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.dao.UserDAO;
    
    public class SignupController extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	protected void doPost(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    
    		String name = request.getParameter("fullname");
    		String email = request.getParameter("email");
    		String password = request.getParameter("password");
    		String gender = request.getParameter("gender");
    
    		UserDAO userDAO = new UserDAO();
    
    		int result = userDAO.createUser(name, email, password, gender);
    		if (result == 1) {
    			response.sendRedirect("success.jsp");
    		}
    	}
    }
    

     

    Also read :

  • Gridview in struts 2 using jQuery DataTable plugin
  • CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax
  •  

    UserDAO

     
    Create a class that performs registration and authentication operation in database
     

    package com.dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    
    import com.jdbc.DBUtility;
    
    public class UserDAO {
    
    	private Connection dbConnection;
    	private PreparedStatement pStmt;
    
    	private String SQL_SELECT = "SELECT name FROM users WHERE email = ? AND password = ?";
    	private String SQL_INSERT = "INSERT INTO users (name,email,password,gender) VALUES (?,?,?,?)";
    
    	public UserDAO() {
    		dbConnection = DBUtility.getConnection();
    	}
    
    	public String verifyUser(String email, String password) {
    		String userName = null;
    		try {
    			pStmt = dbConnection.prepareStatement(SQL_SELECT);
    			pStmt.setString(1, email);
    			pStmt.setString(2, password);
    			ResultSet rs = pStmt.executeQuery();
    			while (rs.next()) {
    				userName = rs.getString("name");
    			}
    		} catch (Exception e) {
    			System.err.println(e.getMessage());
    		}
    		return userName;
    	}
    
    	public int createUser(String name, String email, String password,
    			String gender) {
    		int result = 0;
    		try {
    			pStmt = dbConnection.prepareStatement(SQL_INSERT);
    			pStmt.setString(1, name);
    			pStmt.setString(2, email);
    			pStmt.setString(3, password);
    			pStmt.setString(4, gender);
    			result = pStmt.executeUpdate();
    		} catch (Exception e) {
    			System.err.println(e.getMessage());
    		}
    		return result;
    	}
    }
    

     

    DBUtility

     
    Next let us create a utility class to handle connections to database.
     

    package com.jdbc;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class DBUtility {
    private static Connection connection = null;
    
    public static Connection getConnection() {
    	if (connection != null)
    		return connection;
    	else {
    		// database URL
    		String dbUrl = "jdbc:oracle:thin:@localhost:1521:XE";
    		try 
    		{
    		Class.forName("oracle.jdbc.driver.OracleDriver");
    		// set the url, username and password for the database
    		connection = DriverManager.getConnection(dbUrl, "system", "admin");
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return connection;
    	}
    	}
    }
    

     
    In addition to above files there are 2 other jsp pages,
    1. welcome.jsp page which get displayed when the user logged into the application.
    2. Success.jsp page which gets displayed once user registration is successful.

    I have not showcased up these files here, you may download the files to see complete example.

    Note: Since this article is intended to demonstrate the usage of tabs feature in jquery, so I have not included any validation parts in it.
     

    Demo

     
    On running the application

    Tab Style Login and Signup jQuery in Java2
     
    On clicking Signup tab

    Tab Style Login and Signup jQuery in Java3

     

    dwd2
    Download It – TabStyleLogin.zip

     

    About Mohaideen Jamil


    Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

    • Srinu k

      Nice and simple article

    • kalpanaben591

      thanks

      • http://www.simplecodestuffs.com Mohaideen Jamil

        Most welcome :)