Saturday, 27 December 2014

Struts2 Login/Register web application using JDBC Drivers

In this post I will explain in detail about how to create, simple Employee login and register web project using struts2 framework with Java, JDBC drivers and ofcourse MVC.

 First Things First :

 We will be needing these jars and libraries for developing web application,


 Flow of Project :



  • First user (Employee) have to registers himself with all valid information needed, then he will get registered with provided username and password, then will redirected to the login page. If any mistake occurs or any duplicate username provided user will be redirected to the Error Page.
  • In case of login if user is a registered user, user will be able to login to site with registered username and password, will be able to see successful login page. If any error occurred the user will be redirected to the Error page. 


 Project Structure with Eclipse :




               Now lets take a look at the MVC patters we have used here, 


  • Model : Model represents an object or JAVA POJO carrying data. In this project Model part is in "com.ron.Model" package.(Bussiness Logic)
  • View   : View represents the visualization of the data that model contain, In this project View part is where all JSP pages are kept.
  • Controller :  Controller acts on both Model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps View and Model separate. In this Project every other packages than model and view will be controller.   
  
Now lets see the files one by one,

JdbcConnection.java :


package com.ron.util;

import java.sql.*;

public class JdbcConnection {
  
 private static Connection conn = null;
 
 public static Connection getConnection(){
  
  try{
   Class.forName("com.mysql.jdbc.Driver");
   conn =  DriverManager.getConnection("jdbc:mysql://localhost:3306/database", "root", "root"); 
  }catch(Exception ex){
   System.out.println("Problem Occured while getting connection to the Database = " + ex.getMessage());
   //ex.printStackTrace();
  }
  return conn;
 }
 
 public static void CloseConnection(){
  try{
   if(conn != null){
    conn.close();
   }
  }catch(Exception ex){
   System.out.println("Problem Occured while Closing the connection to the Database");
  }
 }
}


In this file we are actually making connection with database using Jdbc drivers, we will use this class and its static whenever we will to get connect/disconnect with the database. Make sure you have Mysql database on port 3306 and also have schema named "database". Or if you have some other setups like other database "Oracle/plsql", other port number then you can make changes to this file (Be careful while making changes).

DaoImplementation.java :


package com.ron.DaoImple;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.ron.Dao.Dao;
import com.ron.Model.Employee;
import com.ron.util.JdbcConnection;

public class DaoImplementation implements Dao{

 private Connection conn = (Connection)JdbcConnection.getConnection(); 
 private ResultSet resultSet = null;
 private Statement stmt = null;
 private Employee emp = new Employee();
 private String sql_query;
 private PreparedStatement pstmt = null;
 
 @Override
 public boolean addEmployee(Employee employee) {
  boolean status = false;
  if(employee!=null){
  sql_query = "INSERT INTO database.employee VALUES(?,?,?,?,?)";  
  try {
   pstmt = conn.prepareStatement(sql_query);
   pstmt.setInt(1, employee.getEid());
   pstmt.setString(2,employee.getEname());
   pstmt.setString(3, employee.getUsername());
   pstmt.setString(4, employee.getPassword());
   pstmt.setString(5, employee.getAddress());
   status =  pstmt.execute();
   
   System.out.println("Value of status in addEmployee = " + status);
  } catch (SQLException e) {
   System.out.println("Problem Occured while inserting Employee");
   e.printStackTrace();
  }
  }else{
   System.out.println("Please provide valid employee to add");
  }
  return !status;
 }
 
 @Override
 public boolean getEmployee(Employee employee){
  boolean status = false;
  List elist = getAllEmployee();
  if(employee!=null){
   Iterator EmployeeIterator = elist.iterator();
   
   while(EmployeeIterator.hasNext()){
    emp = EmployeeIterator.next();
    if(employee.getUsername().equals(emp.getUsername())){
     System.out.println("Username is not Available!!!");
     return false;     
    }
   }
   
   
   sql_query ="SELECT * FROM database.employee where username='"+employee.getUsername()+"' and password='"+employee.getPassword()+"'";
   System.out.println(sql_query);
   try{
    stmt = conn.createStatement();
    resultSet = stmt.executeQuery(sql_query);
    
    while(resultSet.next()){
     emp.setEid(resultSet.getInt(1));
     emp.setEname(resultSet.getString(2));
     emp.setUsername(resultSet.getString(3));
     emp.setPassword(resultSet.getString(4));
     emp.setAddress(resultSet.getString(5));
    }
    
    if(emp.getUsername().equals(employee.getUsername()) && emp.getPassword().equals(employee.getPassword()) ){
     status = true;
    }else{
     status = false;
    }
   }catch(Exception e){
    System.out.println("Problem Occured while getting logincheck = " + e.getMessage());
   }
  }
  return status;
 }
 
 
 public List getAllEmployee(){
  List emplist = new ArrayList();
  sql_query ="SELECT * FROM database.employee";
  try{
   
   stmt = conn.createStatement();
   resultSet = stmt.executeQuery(sql_query);
   
   while(resultSet.next()){
    emp.setEid(resultSet.getInt(1));
    emp.setEname(resultSet.getString(2));
    emp.setUsername(resultSet.getString(3));
    emp.setPassword(resultSet.getString(4));
    emp.setAddress(resultSet.getString(5));
    /*if(!emp.equals(null)){
     System.out.println("Name of employee @Addding : " + emp.getEname());
    }*/
    emplist.add(emp);
   }
  }catch(Exception ex){
   System.out.println("Problem Occured while getting All Employee");
   ex.printStackTrace();
  }
  return emplist;
 }
 
}

In this file we are using the Connection object returned by getConnection() method of JdbcConnection class. In DaoImplementation class we have three important met hods which runs queries for Inserting a Employee Object to database, and Getting the Employee Object from the database also we have a method to get all Employee objects from the database. We will be using these class's methods to insert and retrieve records from database.


OnlyAction.java :


package com.ron.Action;

import com.opensymphony.xwork2.Action;
import com.ron.Form.Form;
import com.ron.Model.Employee;

public class OnlyAction exteds ActionSupport{
 private Form form = new Form();
 private Employee employee = new Employee();
 
 public Form getForm() {
  return form;
 }
 public void setForm(Form form) {
  this.form = form;
 }
 public Employee getEmployee() {
  return employee;
 }
 public void setEmployee(Employee employee) {
  this.employee = employee;
 }
 
 public String loginMethod(){
  String status = Action.ERROR;  
  
  getEmployee().setUsername(getForm().getUsername());
  getEmployee().setPassword(getForm().getPassword());
  
  if(getForm().getService().getDao().getEmployee(getEmployee())){
   status = Action.SUCCESS;
  }else{
   status = Action.ERROR;
  }  
  return status;
 }
 
 
 public String registerMethod(){
  String status = "error";
  
  getEmployee().setEid(getForm().getEid());
  getEmployee().setEname(getForm().getEname());
  getEmployee().setUsername(getForm().getUsername());
  getEmployee().setPassword(getForm().getPassword());
  getEmployee().setAddress(getForm().getAddress());
  
  if(getForm().getService().getDao().addEmployee(getEmployee())){
   status = Action.SUCCESS;
  }else{
   status = Action.ERROR;
  }
  return status;
 }   
}

OnlyAction.java weird name, yeah I know!! but suits it, because it contains only actions which will be triggered by user from the jsp pages. It means when user provides username and password and try to login inside system "loginMethod()" will get called and then loginMethod() will call its underlying DaoImplementations methods which will communicate with database to get appropriate result (same goes with registerMethod() too). According to the result returned by the DaoImplementation methods OnlyAction class will forward a String object to the "Struts.xml" file, which will then decide where to redirect the control of web application. 
In this class I have created a Instance of class Form, through which we can access Service class's methods, Dao class's methods, DaoImplementation class's method and also Jsp forms fields. And make sure you have get/set methods for every instance variable so that internally struts could use them. 

Struts.xml :


 
  
   success.jsp
   error.jsp
  
  
   index.jsp
   error.jsp
  
 

This file is mainly responsible for redirecting control from one jsp page to another, with respect to the String object coming from OnlyAction class's methods. It contains Struts2 tags Defined by dtd used above in this file. In between struts tags we specify action tags which specify which class's method is going to get called when user perform any operation, According to that result it will move control to next jsp page. 


index.jsp :

    

Login

&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspSignUp Now!!!


In index.jsp file we have used <form></form> tags to create the login user interface this form has a action name which will be after submission get matched with struts.xml's action if it matches then particular method will get call control flow will be depends on Action class's returned String object (Same goes with registerAction class). 


Take a look at the snapshots of this project,


Login Window


























If login Successful you will be redirected to the Success page, and if failed you will be redirected to the Error page.
Success Page



























Error Page































Register Page


























If user registers successfully then he will be redirected to the Login Page, Otherwise redirected to the Error Page.
Good Luck.(download, run and make changes to this project.)


Download project in war file... 

If you like this post, please comment,like & share with friends.... 






5 comments:

Unknown said...

thank u for this article.Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging…

java training institutes in chennai | java j2ee training institutes in velachery

IT Tutorials said...

perfect explanation about java programming .its very useful.thanks for your valuable information. java training in chennai | java training in velachery

Unknown said...

Hi Rohan Pandhare, I'm having issues understanding how does the form is initialy created once the user enters all his data through the register.jsp. I don't understand the "mapping". How does the data end up in a Form object?

Anonymous said...

Thank you for sharing this blog. This is awesome blog for beginners. This will help to improve my JAVA knowledge.
Struts Training in Chennai | Struts Training | Struts Training center in Chennai | Struts course in Chennai

velraj said...


I feel this is good. I wish to read this. I need more good article like this.
Struts Training in Chennai
struts course
Struts Training in Tambaram
Wordpress Training in Chennai
Wordpress Training Chennai
Spring Training in Chennai
Hibernate Training in Chennai
Struts Training in Chennai

Post a Comment

If you have any issue regarding this post, Please comment and I will try to solve you issues asap..