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






Friday, 19 December 2014

Java : Integrating JTable Plugin Struts 2 & Hibernate 3 Using Ajax & JQuery

          

In  this web  project  I  will  explain  in  depth about how  to  perform  CRUD (create,read,update & delete) operation on single page using JTable,JQuery plugins integrating with Struts2 & Hibernate3 via Ajax. Our final outcome window with JTable with dynamic database values will  look like,

Jtable Window
here you can perform CRUD operation without redirecting to the new page.

First Things First :

Essential Jars and Libraries required for this project :
*(Please try to get the correct version of jars )

Now  lets  follow  it  step  by  step  to  create  a  web  project,  I  am  using eclipse(kepler) for creating this project, in other IDE's project structure and required files may be different.
Eclipse IDE : project->dynamic web project->(name it)->hit Enter.
Finally our project structure will look like,




Final Project Structure

Lets take a look at content of project one by one,
Struts.xml                                                                                                                            
















The "struts.xml"  file contains  configuration  information  for  redirecting according to the actions generated by end-users, It  will  take  the request generated by users and redirect it to that respective action. Here name of package is "default"(it  can be anything), and extends "json-default" which creates dependency with struts2-json-plugin.2.x.x.jar file.
In action  tag, name implies  every action name will be followed by "Action" text, class attribute show that on every action methods will be called from JtableAction.class  file. Result attribute show we will be redirecting to the same page  "index.jsp" as outcome of every action. 

Web.xml                                                                                                         

In this web.xml is a J2EE configuration file, It has no role than how web container is going to process the elements of the HTTP request generated by end-users.  

Hibernate.cfg.xml                                                                                           



















This file is going to have the Hibernate and database related configurations like database driver class, exactly on which port we are going to find our database, username and password for database access, Hibernate dialect for mysql database. Also it will contain direct mapping of the model file which we are going to use in our projects.(All model classes are exact copies from database in beans format). 
Note**:  To run this file you must have MySQL database "krishiseva" and table named Employee with all necessary fields that we are using in project, or you can change  it according to your requirement like,  if  you  are  using  Oracle database   you  must  need  to  change  database  Drivers,  Dialect  and  port accordingly. And if you are changing table related data, then you must change all related things. 


 Employee.hbm.xml                                                                                         





















It is a model(POJO) class configuration file, which shows exact fields from database with their types and size. We have to be careful with matching names, types and sizes of the fields from actual database tables. If someone wants to user more than one database tables then, there must be exact number of pojo/model class as well as "hbm.xml" file.


EmployeeTableJtable.js                                                                                                    


























This file is responsible for creating actual rendering of the Jtable on webpage, we have to link it from the index.jsp page where we want to  display our table. It is defining a Jtable container "EmployeeTableContainer"  which we have to load on respective jsp page. It also contains list of all Actions that user will be generating while using Jtable. It also shows the "fields" that will be visible on Jtable (**note : fields name must match with model class's variable names) , Field: title will be the name of table column that will get displayed on jsp page.

Employee.Java                                                                                                


















This file is just Plain Old Java File, its name must be same to the table in the database which we want to use. Also it should contains all the fields from database tables as variables in POJO class.



HibernateConfig.java                                                                                       























This file will be used to get the connection Object to the database, Which have two static methods getSession and CloseSession.



DaoImple.java                                                                                                 













This file will be actually interacting with database/tables to fetch and store data in the database. It have  four important methods list(), updateEmployee() ,addEmployee() and deleteEmployee(). which will be used by hibernate to generate HQL queries over SQL wrapper. This all methods will be used by JTableAction class with respective actions generated by users.

JtableAction.java                                                                                            






This file is main action class, which will be responsible for linking its methods with actions defined in the EmployeeTableJTable.js .

Index.jsp                                                                                                         





















This is the jsp page where all of our data will be displayed, also now all Jtable html tags will be generated automatically . We just have to show the Jtable Container in division tag in side the html body tag.
 Now finally run this project from eclipse environment with available server, and use Jtable to perform CRUD operation on database.

Adding an Record to the database:
 By Clicking the add record button on the page, a new Popup window will appear which will let us add a new record to database table.


Insert Employee Record
                                           
 By putting proper values inside text boxes, it will be possible for you to insert new record in the database table.
Deleting an Record from the database: 
 By clicking the respective delete button to the record, we can delete that record from Jtable view as well as database table.


Delete Employee

Updating an Record from the database:

By clicking the update button related with particular record, a update record will appear with previously present values. Make change in values, after submitting changes will reflect in Jtable as well as Dabase table.

Edit Record
 Good luck for using Jtable plugin.
for more information about JTable.org
 Download the Source code in War file,