Pages Navigation Menu

Coding is much easier than you think

CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax

 
Struts-2-jTable-jQuery-plug-in-Create-record-animation-effect
 
In the previous article “Setting up jQuery jTable plugin with Struts 2 framework” I have explained about how to setup jTable plugin in struts 2 application. This article describes on how to implement “Ajax based curd operation in Struts 2 using the JQuery jTable plugin, If you have not read the previous articles “Setting up jQuery jTable plugin with Struts 2 framework” I will recommend that you read that article first because it explains what jTable plugin is and how you can integrate it in Struts 2 application.
 

Steps done to set up our application for jTable

 
Libraries required for the setup,

 
Create a dynamic project in eclipse and setup above required libraries as explained here. The final project structure of this looks as below.
 
crud in struts 2 using jTable plugin
 
Setup from the browser perspective: jTable
 

JSP

 




jTable in Struts 2













AJAX based CRUD operation in Struts 2 using jTable plugin

 

JS file for implementing CRUD

 

$(document).ready(function() {
	$('#StudentTableContainer').jtable({
		title : 'Students List',
		actions : {
			listAction : 'listAction',
			createAction : 'createAction',
			updateAction : 'updateAction',
			deleteAction : 'deleteAction'
		},

		fields : {
			studentId : {
				title : 'Student Id',
				width : '30%',
				key : true,
				list : true,
				edit : false,
				create : true
			},
			name : {
				title : 'Name',
				width : '30%',
				edit : true
			},
			department : {
				title : 'Department',
				width : '30%',
				edit : true
			},
			emailId : {
				title : 'Email',
				width : '20%',
				edit : true
			}
		}
	});
	$('#StudentTableContainer').jtable('load');
});

 
I have explained the working of above jTable js file in my previous article “Setting up JQuery jTable plugin in Struts 2”, hence I’m not going to explain it again.
 
Now create a student table in Oracle database using the query below. On this table we are going to perform CRUD operation via ajax
 

create table Student(studentid int,name varchar(50),department varchar(50),
email varchar(50));

 

CurdDao

Create a class that performs CRUD operation in database
 

package com.dao;

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

import com.jdbc.DataAccessObject;
import com.model.Student;

public class CrudDao {

private Connection dbConnection;
private PreparedStatement pStmt;

public CrudDao() {
	dbConnection = DataAccessObject.getConnection();
}

public void addStudent(Student student) {
	String insertQuery ="INSERT INTO STUDENT(STUDENTID, NAME," +
			"DEPARTMENT, EMAIL) VALUES (?,?,?,?)";
	try {
		pStmt = dbConnection.prepareStatement(insertQuery);
		pStmt.setInt(1, student.getStudentId());
		pStmt.setString(2, student.getName());
		pStmt.setString(3, student.getDepartment());
		pStmt.setString(4, student.getEmailId());
		pStmt.executeUpdate();
	} catch (SQLException e) {
		System.err.println(e.getMessage());
	}
}

public void deleteStudent(int userId) {
	String deleteQuery = "DELETE FROM STUDENT WHERE STUDENTID = ?";
	try {
		pStmt = dbConnection.prepareStatement(deleteQuery);
		pStmt.setInt(1, userId);
		pStmt.executeUpdate();
	} catch (SQLException e) {
		System.err.println(e.getMessage());
	}
}

public void updateStudent(Student student)  {
	String updateQuery ="UPDATE STUDENT SET NAME = ?," +
			"DEPARTMENT = ?, EMAIL = ? WHERE STUDENTID = ?";
	try {
		pStmt = dbConnection.prepareStatement(updateQuery);
		pStmt.setString(1, student.getName());
		pStmt.setString(2, student.getDepartment());
		pStmt.setString(3, student.getEmailId());
		pStmt.setInt(4, student.getStudentId());
		pStmt.executeUpdate();

	} catch (SQLException e) {
		System.err.println(e.getMessage());
	}
}

public List getAllStudents() {
	List students = new ArrayList();

	String query = "SELECT * FROM STUDENT ORDER BY STUDENTID";
	try {
		Statement stmt = dbConnection.createStatement();
		ResultSet rs = stmt.executeQuery(query);
		while (rs.next()) {
			Student student = new Student();

			student.setStudentId(rs.getInt("STUDENTID"));
			student.setName(rs.getString("NAME"));
			student.setDepartment(rs.getString("DEPARTMENT"));
			student.setEmailId(rs.getString("EMAIL"));
			students.add(student);
		}
	} catch (SQLException e) {
		System.err.println(e.getMessage());
	}
	return students;
}
}

I hope the above code is self explanatory
 
Setup from the server’s perspective: Servlet
 
In Struts 2 Action class, I have defined 4 method- create, read, update and delete to perform CRUD operations. Since jTable accepts data only in Json format, so we are converting this List (Java Object) to Json(Javascript object Notation) format using struts2-json-plugin.jar.

**Update: In the article AJAX implementation in Struts 2 using JQuery and JSON I have explained in detail about how to use struts2-json-plugin.jar clearly, So if you are not aware of how struts2-json-plugin works, then please go thorough the above mentioned link.
 

Action class

 

package com.action;

import java.io.IOException;
import java.util.List;

import com.dao.CrudDao;
import com.model.Student;
import com.opensymphony.xwork2.Action;

public class JtableAction {
	
	private CrudDao dao = new CrudDao();

	private List records;
	private String result;
	private String message;
	private Student record;

	private int studentId;
	private String name;
	private String department;
	private String emailId;

	public String list() {
		try {
			// Fetch Data from Student Table
			records = dao.getAllStudents();
			result = "OK";
		} catch (Exception e) {
			result = "ERROR";
			message = e.getMessage();
			System.err.println(e.getMessage());
		}
		return Action.SUCCESS;
	}

	public String create() throws IOException {
		record = new Student();
		
		record.setStudentId(studentId);
		record.setName(name);
		record.setDepartment(department);
		record.setEmailId(emailId);
	
		try {
			// Create new record
			dao.addStudent(record);
			result = "OK";

		} catch (Exception e) {
			result = "ERROR";
			message = e.getMessage();
			System.err.println(e.getMessage());
		}
		return Action.SUCCESS;
	}

	public String update() throws IOException {
		Student student = new Student();
		
		student.setStudentId(studentId);
		student.setName(name);
		student.setDepartment(department);
		student.setEmailId(emailId);
		
		try {
			// Update existing record
			dao.updateStudent(student);
			result = "OK";
		} catch (Exception e) {
			result = "ERROR";
			message = e.getMessage();
			System.err.println(e.getMessage());
		}
		return Action.SUCCESS;
	}

	public String delete() throws IOException {
		// Delete record
		try {
			dao.deleteStudent(studentId);
			result = "OK";
		} catch (Exception e) {
			result = "ERROR";
			message = e.getMessage();
			System.err.println(e.getMessage());
		}
		return Action.SUCCESS;
	}

	public int getStudentId() {
		return studentId;
	}

	public String getName() {
		return name;
	}

	public String getDepartment() {
		return department;
	}

	public String getEmailId() {
		return emailId;
	}

	public void setStudentId(int studentId) {
		this.studentId = studentId;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}
	public Student getRecord() {
		return record;
	}

	public void setRecord(Student record) {
		this.record = record;
	}

	public List getRecords() {
		return records;
	}

	public String getResult() {
		return result;
	}

	public String getMessage() {
		return message;
	}

	public void setRecords(List records) {
		this.records = records;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public void setMessage(String message) {
		this.message = message;
	}
}

 
If you read my article on CRUD Operations in Java Web Applications using jTable jQuery plugin via Ajax then you might have noted once difference here, i.e. I have not created any request or response object in action class to get the student parameters, because those parameter from jsp file auto bounded to my struts 2 action, this is done via struts2-jquery-plugin. One only requirement for this parameter to be passed from jsp is, you have create the member variable for those parameter in action class along with getters and setters as in above file.
 

You might be interested to read:

  • GridView in struts 2
  • Ajax implementation in Struts 2 without jQuery plugin
  • Tab Style Login and Signup example using jQuery in Java web application
  •  
    I have explained in detail about difference response generated for create, read, update and delete operation in the article CRUD Operations in Java Web Applications using jTable jQuery plugin via Ajax, So please refer to this article mentioned above, if you are not aware of the different response created for CRUD operation in Jtable plugin.
     

    Jtable Issue related to Struts 2

     
    As mentioned in my previous article , the property names of jTable plugin are case sensitive. Only “Result”, “Records” and “Message” will work. In struts 2 the “json response” generated is in lower case[“result”, “records” and “message”], hence I edited the jtable.js to replace Result to result, Records to records and Message to message then it worked.

    **Note: Along with the above keyword replace TotalRecordCount to totalRecordCount, since this parameter will be used to display pagination count (Which I will implement in upcoming tutorial)

     

    Model class

     
    Create Model class used in the controller, which will have getters and setters for fields specified in jTable script.

    package com.model;
    
    public class Student {
    
    	private int studentId;
    	private String name;
    	private String department;
    	private String emailId;
    
    	public int getStudentId() {
    		return studentId;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public String getDepartment() {
    		return department;
    	}
    
    	public String getEmailId() {
    		return emailId;
    	}
    
    	public void setStudentId(int studentId) {
    		this.studentId = studentId;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public void setDepartment(String department) {
    		this.department = department;
    	}
    
    	public void setEmailId(String emailId) {
    		this.emailId = emailId;
    	}
    }
    

     

    DAO Class

     
    Create utility class which connect to database Using Oracle JDBC driver

    package com.jdbc;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class DataAccessObject {
    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;
    	}
    	}
    }
    

     

    Struts.xml

     
    Make sure that you have the following mapping in struts.xml

    
    	
    		
    			/index.jsp
    		
    		
    			
    		
    	
    
    

     

    web.xml

     

     
       struts2
       
    		org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    
     
     
       struts2
       /*
     
     
       index.jsp
     
    

     

    Demo

     
    On running the application
     
    Integrating-jQuery-jTable-plugin-with-Struts2-framework
     
    On clicking ‘Add new record’
    Struts-2-using-jTable-jQuery-plug-in-Create-record
     
    Now the new record will be added with fade out animation
    Struts-2-jTable-jQuery-plug-in-Create-record-animation-effect
     
    On clicking edit button
    Struts-2-jTable-jQuery-plug-in-Update-record
     
    On clicking delete button
    Struts-2-jTable-jQuery-plug-in-Delete-record
     
    In the next article Pagination in Struts 2 using jQuery jTable plugin I have implemented paging feature in the CRUD example.
     
    download

     

    Reference

     
    jTable official website
    AJAX based CRUD tables using ASP.NET MVC 3 and jTable jQuery plug-in
     

    69 Comments

    1. Hi jamil,

      I am trying to debug the above code, i am clicking on add new record and entering the new record and then clicking on save,after clicking on save i am getting error message error communicating to server and in JSPAction classs it is entering the createaction method but it is no setting the propert of student class,

      can anyone pelase help?

    2. hi jamil,
      I hava two tables for example student table and person table.I want to put these two tables in struts.xml but I can’t multiple action error occur.plz,tell me.What should I do?

    3. hi jamil,

      I want to know how to add multi table in struts.xml. pls,, tell me how to do….

    4. hi jamil,

      I am using tiles as result type is necessary to use result type json .. because i want shoe in pertecouelr tiles i got list in jtable.jsp but its not showing in jtable please suggest me thanks in advance

    5. hi jamil ,
      i want to need result type tiles and in tiles i want to show this table …..please tell me how i set list value in jtable.

    6. Hi Jamil, wondering if you can please shed some light on this. Thanks

      I have your example working with struts 1.2. On the server side MYTableActions class I am getting the values sent from JTable via request object. In the struts xml file I am just declaring a dummy form which I don’t even use. My question is about how to handle the requirement of struts 1.2 and its ActionForm form. In the struts xml config file its expecting an action form name. JTable does not use form JSP form beans.
      Can I invoke the struts action without having to use a form on server side?. The name parameter in the struts xml file appears to be mandatory.

    7. Hi Jamil, is it possible to have a cascading dropdown box appear on the popup dialog for example Country as primary drop down and state as the cascading drop-down. The drop-downs would be populated from the server via Ajax calls. Not sure if this possible using JTable? Thanks

    8. Hi Jamil great tutoria

      A problem i can display the list from my db but when i add new record i can’t…the firebug tell this:

      jTable ERROR: Server must return the created Record object.

      What can i do??
      Thanks for the help in advance

    9. hi Jamil…i can display the list from the database but i can’t add new record from de firebug says:

      jTable ERROR: Server must return the created Record object.
      I did the lower case thing but this error i can correct help please

    10. issue of displaying data occurs no display data in jtable

    11. thanks Jamil… i have one more issue i have integrated ur code in project ….in my jsp i am able display the jtable but getting the message in table as ‘No Data Found’ and alert error as ‘Error occured while communicating to server’.

      In my action class i have declared one list and along with its getters & setters. and also the field variables in js file are same as my pojo class attributes.

      please let me know where i am making an mistake

      • Hi,

        Sorry for delay. Please upload your code at dropbox and share me your link

        • Hi Jamil,
          below is the link of war file i have uploaded…please look into the code and correct me if i went somewhere wrong…i am not able to display the data on jsp page…its only showing json array…kindly help
          https://www.dropbox.com/s/ng8r68akm5z6kij/AjaxCurdjTableStruts2.war?dl=0

          • hi jamil any solution you found for the problem i have faced…
            i have shared you the war file of my project….

            kindly help

          • Hi Syed,
            Apologies for delay. I’m a certain configuration issues in your war files. I could not able to run your war file in my local space, so i dint got any time to look at the exact issue. How ever the war I have uploaded works fine from my end, Please tweak the code accordingly.

    12. can u please tel me what is jTable.jsp defined in your struts2 config file….
      i am facing an issue while integrating ur concept in my project

      request you to le me know

      • Hi sorry for typo.. its index.jsp. Refer screen shot.

        • one more help please….i am not able to populate the data in the jsp page…i am getting the message as no data available and error alert message saying that “Error Occured while communicating to the server”

          i have the getters and setters in my action class and the fields i have written in js file are matching with my pojo class attributes

          kindly help

    13. Hello Jamil,
      I have implemented each and every thing, but list method of action class is not getting called.
      i have mentioned it inside the struts.xml and i have wrote right script.
      help me its urgent.
      waiting for reply…

    14. Can i add button in forum as “like buttton” in the jtable. So if any body press the “like” button i want to add the count?

      • Yes this feature can be implemented . Please refer jTable official web blog

        • Thanks for your replay Mohaideen. I want to implement forum like page which should have hyperlinks for that which will be best JTable or jquery Datatable. In jquery datatable am getting datas from database and displaying in JSP using . In this the datas are displaying in JSP but the div which will form above and below the table for showing entries, search, first,next button are not generating. If database is best please help to solve this issue. I think you are clear with my issue. Please reply

          • * In JSP am displaying using “s:iterator”

          • Hi ,

            All the above scenario can be easily implemented in Jtable plugin.

            For search functionality you need to add a button in jTable header and handle its server side via ajax

    15. helo jamil..
      can u please tell me how to add validation in jquery jtable struts2 CRUD

    16. hi.. jamil..
      I mostly refer ur tutorial becoj ur tut practically very useful.
      i am new in struts2. can u plz suggest me to show server side validation error msg represent in particular record adding window.N one more thing is Jquery have embeded a datepicker jquery.
      regards: sunil tariyal

    17. Hi,

      I am a newbie i am trying to replicate the example but i don’t know how to get the required jars i am having maven integration with my eclipse please suggest me how to get the jars

      • get the required jar files from the source of struts software by doing build path in eclipse

    18. not showing add button and not work properly

    19. Hi, jamil

      All are working fine, except “no Data are displayed on JqJtable”, instead blank rows only , i added
      [code]

      ……. [/code]
      but not displaying any datas, sure the all records are fetched from database to Action class but not to jqJtable, also i changed the jqueryJtable.js file of my project with .js file that were downloaded from this site
      please help…….

      • the codes tags are not working….:) :
        i added code :

    20. Hi Jamil,
      I’m looking for a way to refresh display tag according to radio boutton checked?
      I have a lot of list that will be displayed using display tag .
      Now i’m looking for a way to display appropriate list according to radio boutton checked ? Does this exist ? What i would use to implement it ? Thank you in advance

      • Use div and different display table for different list, toggling between div can be implemented via jquery

        • Hi jamil,
          I tried and it worked well..Thank you
          Now i’m facing to another problem. Can i make row of display tag clickable? Even it’s the case, is there a way to know which row Id has been clicked ? Because i want to make rows clickable, and when the user click on row, he can modify its properties and when he validate these properties change also in database. do you understand what i mean?

    21. Hello,
      Great Example. Everything works like a charm but only the add new record dialog box does not disapper after adding the record neither it refreshes the table. The getJSONResult contains the value of records which includes the new added record but there lies the problem.

      • Which browser are you using. Please upload your source code in dropbox and share me the link

      • You replaces Records, Message and Response with records,message and response (Or use Jamil’s previous tutorial’s jquery.jtable.js) but you didnot replace Record with record replace them, or use the jtable jquery that jamil provided in this tutorial :) (previous one didnt need to add rows so he didnt replace Record with record in there)

    22. hey! your example is wonderful. I have been able to generatee list, make update but while making update my code runs fine and data is also updated in the database but the table on pressing ‘save’ shows error. Any idea how to refresh the table on update??

    23. how to develop same example in spring mvc hibernate with ajax and jquery json response

    24. Hi Jamil

      Can you please share a code which would have drop-down in create box, drop-down should fetch value of database.

    25. Hi Jamil

      I am facing one problem in my project, i am able to generate required JSON, but for that i have made configuration in struts.xml as i struts2-json plugin was not not generating JSON. So i made the action like this.:

      Records
      {“Result”:”OK”,”Records”:
      }

      here Records is a array list of some bean class.

      below is my JSON:

      {“Result”:”OK”,”Records”:[{“areaIdSingle”:”KAAMPI”,”capacityIdSingle”:”KAAMPI23″,”citySingle”:”HELSINKI”,”maxCapacitySingle”:”787″,”minCommittedCapacitySingle”:”787″,”networkInfoSingle”:”hjh”,”rateSingle”:”787.0″,”skillSingle”:”installationVDSL”,”technologySingle”:”VDSL”,”workQueueNameSingle”:”hjh”},{“areaIdSingle”:”SEC-15″,”capacityIdSingle”:”SEC-1512″,”citySingle”:”GURGAON”,”maxCapacitySingle”:”7878″,”minCommittedCapacitySingle”:”78787″,”networkInfoSingle”:”hjhjh”,”rateSingle”:”777.0″,”skillSingle”:”reInstallationADSL”,”technologySingle”:”ADSL”,”workQueueNameSingle”:”hjhjh”},{“areaIdSingle”:”SEC-15″,”capacityIdSingle”:”SEC-1523″,”citySingle”:”GURGAON”,”maxCapacitySingle”:”787″,”minCommittedCapacitySingle”:”787″,”networkInfoSingle”:”jh”,”rateSingle”:”87.0″,”skillSingle”:”installationVDSL”,”technologySingle”:”VDSL”,”workQueueNameSingle”:”jh”}]}

      • Hi Can you post your code again using the tag below ..

        [code]Your code here.. [\code]

        • I solved out that issue. :)

    26. Its a wonderful example.. but i am still confused on how to move from one jsp page to another jsp using the action.. could you please help on this aspect.

    27. Hai jamil

      {“app”:1,”message”:null,”record”:null,”records”:[{“do”:”Indi”,”do”:1,”don”:”asdasd”}],”result”:”OK”}
      where we have change option,message and records in jquery.jtable.js pls help me .if u have help this pls help me

      • Hi open jtable.jquery.js file , in which replace Result to result, Records to records and Message to message.

        • by default those result and records and message are lowercase .still same error will come pls i have kept setters and getters also in action jamil pls help as soon as possiable

          • Hi this is what the changes I made. I’m not sure what else you missing.. Please upload your code in dropbox and share me the link

    28. where you are writing getJSONResult action in jsp..pls help me as soon as possiable pls

      • Hi,

        I used that action to test my json responce returned from struts 2 action(Refer my previous article on jtable + struts 2).

        I just used it for testing purpose and You can remove it.

    29. Hi how can one add webservice in this example please help…

    30. Hi tI tried this code,add,updatiing and deleting records functionality works fine, but my table data doesnt load in the jTable :(

      • I made a small mistake, need to update my code.. Please add the tag < !DOCTYPE html> before <html> tag, then it will work fine

        • Thanks Buddy, you have written a pretty descent code,thanks !!!

        • Thanks buddy :)

    31. I am not been able to view anything in uotput except html header. please help i that regards

      • Hi, this code works fine. download war from available link and try it out. If not working, then share t=your stacktrace

      • hi its been working now. now can you please tell me how to call webservice in this example and create its client

        • Hi I my need to figure out the same. if you had found any solution, then please share us.

    32. thnk you :)