Pages Navigation Menu

Coding is much easier than you think

CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax

Posted by in Ajax, jQuery, Struts-2 | 18 comments

 
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

 

<html>
<head>
<title>jTable in Struts 2</title>
<!-- jTable metro styles. -->
<link href="css/metro/blue/jtable.css" rel="stylesheet" type="text/css" />
<link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet"
	type="text/css" />

<!-- jTable script file. -->
<script src="js/jquery-1.8.2.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
<script src="js/jquery.jtable.js" type="text/javascript"></script>
<!-- User defined Jtable js file -->
<script src="js/userDefinedJtable.js" type="text/javascript"></script>

</head>
<body>
<div style="text-align: center;">
	<h3>AJAX based CRUD operation in Struts 2 using jTable plugin</h3>
	<div id="StudentTableContainer"></div>
</div>
</body>
</html>

 

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<Student> getAllStudents() {
	List<Student> students = new ArrayList<Student>();

	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<Student> 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<Student> getRecords() {
		return records;
	}

	public String getResult() {
		return result;
	}

	public String getMessage() {
		return message;
	}

	public void setRecords(List<Student> 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.
 

Do read:

  • GridView in struts 2
  • Ajax implementation in Struts 2 without jQuery plugin
  • Autocomplete in Java web application using jQuery
  • Dynamic dependent dropdown in Java web application using jQuery
  • 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

     

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
    <struts>
    	<package name="default" extends="json-default">
    		<action name="*Action" class="com.action.JtableAction"
    			method="{1}">
    			<result type="json">/jTable.jsp</result>
    		</action>
    		<action name="getJSONResult" class="com.action.JtableAction" method="list">
    			<result type="json" />
    		</action>
    	</package>
    </struts>
    

     

    web.xml

     

     <filter>
       <filter-name>struts2</filter-name>
       <filter-class>
    		org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    </filter-class>
     </filter>
     <filter-mapping>
       <filter-name>struts2</filter-name>
       <url-pattern>/*</url-pattern>
     </filter-mapping>
     <welcome-file-list>
       <welcome-file>index.jsp</welcome-file>
     </welcome-file-list>
    

     

    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.
     

     

    Reference

     
    codeproject.com/

    Read More

    Autocomplete in Struts 2 using Jquery and JSON via Ajax

    Posted by in Ajax, jQuery, Struts-2

     
    I have already written a detailed post on Autocompleter Textbox & dropdown in Struts 2 using struts2-dojo-plugin.jar. In this post, I am going to describe how to implement Ajax based autocomplete in Struts 2 web application using jQuery plugin. jQuery Autcomplete is part of the jQuery UI library which allows converting a normal textbox into an autocompleter textbox by providing a data source for the autocompleter values.
     
    struts 2 autocompleter_2
     
    Here when user types a character in text box, jQuery will fire an ajax request using autocomplete plugin to Struts 2 action class, which in turn call the dao class which connects to the database and returns the required data back as an array list, this list should be returned in json format to the success function of ajax call. So to handle this you need struts2-json-plugin-2.x.x.jar. This plugin allows you to serialize the Action class attribute (which has getter and setter) into a JSON object. This guide will teach you on how to implementation AJAX in Struts 2 using JQuery and JSON
     

    Library

     
    struts2-json-plugin-2.x.x.jar
    ojdbc14.jar
    jquery-1.10.2.js
    jquery-ui.js
    jquery-ui.css
     
    Now create a dynamic web project in eclipse and add the above jars in classpath of the project and the project structure should look like shown below.
     

    Project Structure


     
    struts 2 autocompleter
     

    Jsp page

    We are done with the setup. Now create a new jsp file under WebContent folder to display the data fetched from database into autocomplete textbox. Now to implement this page with Autocompleter feature and make sure that you referred the jQuery core and jQueryUI libraries.
     

    <%@ taglib prefix="s" uri="/struts-tags"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>Autocomplete in Struts 2 using Jquery and JSON</title>
    <script src="js/jquery-1.10.2.js"></script>
    <script src="js/jquery-ui.js"></script>
    <script src="autocompleter.js"></script>
    <link rel="stylesheet" href="css/jquery-ui.css">
    <link rel="stylesheet" href="style.css">
    
    </head>
    <body>
    	<div class="header">
    		<h3>Autocomplete in Struts 2 using Jquery and JSON</h3>
    	</div>
    	<br />
    	<br />
    	<div class="search-container">
    		<div class="ui-widget">
    			<s:textfield id="search" name="search" />
    		</div>
    	</div>
    </body>
    </html>
    

     

    Js file

     
    Here we get data from database via ajax and apply autocompleter
     

    $(document).ready(function() {
    	$(function() {
    		$("#search").autocomplete({
    		source : function(request, response) {
    			$.ajax({
    				url : "searchAction",
    				type : "POST",
    				data : {
    					term : request.term
    				},
    				dataType : "json",
    				success : function(jsonResponse) {
    					response(jsonResponse.list);
    				}
    			});
    			}
    		});
    	});
    });
    

    When a user types a character in text box ,jQuery will fire an ajax request to the controller, in this case controller is SearchController as mentioned in the above js file.
     
    Recommended reading :

  • AJAX implementation in Struts 2 using JQuery and JSON
  •  

    Business class

     
    Next step is to create a class that would fetch data from database.

    package com.dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.ArrayList;
    
    public class DataDao {
    	private Connection connection;
    
    	public DataDao() throws Exception {
    		connection = DBUtility.getConnection();
    	}
    
    	public ArrayList<String> getFrameWork(String frameWork) {
    		ArrayList<String> list = new ArrayList<String>();
    		PreparedStatement ps = null;
    		String data;
    		try {
    			ps = connection
    					.prepareStatement("SELECT * FROM JAVA_FRAMEWORK  WHERE FRAMEWORK  LIKE ?");
    			ps.setString(1, frameWork + "%");
    			ResultSet rs = ps.executeQuery();
    			while (rs.next()) {
    				data = rs.getString("FRAMEWORK");
    				list.add(data);
    			}
    		} catch (Exception e) {
    			System.out.println(e.getMessage());
    		}
    		return list;
    	}
    }
    

     

    Data Access object

     
    Connecting To Database Using JDBC

    package com.dao;
    
    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;
    	}
    	}
    }
    

     

    Action class

     
    Now Create the action class to handle Ajax call; in action class you need to create instance variables and its respective getter and setter methods since all the variables which have a setter can be set to the values as which are passed as parameters by jQuery and all the variables that have a getter method can be retrieved in the client javascript code.

    package com.action;
    
    import java.util.ArrayList;
    
    import com.dao.DataDao;
    import com.opensymphony.xwork2.Action;
    
    public class AutoCompleteAction implements Action {
    	// Received via Ajax request
    	private String term;
    	// Returned as responce
    	private ArrayList<String> list;
    
    	public String execute() {
    		try {
    			System.out.println("Parameter from ajax request : - " + term);
    			DataDao dataDao = new DataDao();
    			list = dataDao.getFrameWork(term);
    		} catch (Exception e) {
    			System.err.println(e.getMessage());
    		}
    		return SUCCESS;
    	}
    
    	public ArrayList<String> getList() {
    		return list;
    	}
    
    	public void setList(ArrayList<String> list) {
    		this.list = list;
    	}
    
    	public String getTerm() {
    		return term;
    	}
    
    	public void setTerm(String term) {
    		this.term = term;
    	}
    }
    

     
    As mentioned in the code, the action class will call the business service class which in turn creates the necessary connection and returns the data back as an array list.
     
    Also read :

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

    struts.xml

     
    In struts.xml, create a package that extend json-default and specify the result type of your action class inside this package to be json. This package component is present in struts2-json-plugin-2.x.x.jar

    Please read the article on AJAX implementation in Struts 2 using JQuery and JSON to understand about “json-default” package better.
     

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
    <struts>
      	<package name="default" extends="json-default">
    		<action name="searchAction" class="com.action.AutoCompleteAction">
    			<result type="json">index.jsp</result>
    		</action>
    	</package>
    	
    </struts>
    

     

    web.xml

     
    Make sure you have done mapping in web.xml file as given below,

    <filter>
       <filter-name>struts2</filter-name>
    <filter-class>
       org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    </filter-class>
    </filter>
    <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    

     

    Demo

     
    struts 2 autocompleter_2
     


     
    If you have any other suggestion on above topic, do let me know via comments. Don’t forget to share this article for comment moderation with your blogger friends. Read More

    Autocomplete in java web application using Jquery and JSON

    Posted by in Ajax, J2EE, jQuery, Servlet

     
    This article will describe how to implement jQuery Autocomplete in java web application. jQuery Autcomplete is part of the jQuery UI library which allows converting a normal textbox into an autocompleter textbox by providing a data source for the autocompleter values.
     
    Autocompleter in java
     
    Here when user types a character in text box ,jQuery will fire an ajax request using autocomplete plugin to the controller, this controller(Servlet) in turn call the dao class which connects to the database and returns the required data back as an array list. After getting the data we convert this list to json format and return it back to the success function of our ajax call.
     

    Library

     
    gson-2.2.2.jar
    ojdbc14.jar
    servlet-api.jar
    jquery-1.10.2.js
    jquery-ui.js
    jquery-ui.css
     

    Project Structure


     
    Autocompleter in java project structure
     

    Jsp page

    Now create a jsp page with Autocompleter feature and make sure that you referred the jQuery core and jQueryUI libraries.
     

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>Autocomplete in java web application using Jquery and JSON</title>
    <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 src="autocompleter.js"></script>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
    <!-- User defied css -->
    <link rel="stylesheet" href="style.css">
    
    </head>
    <body>
    <div class="header">
    	<h3>Autocomplete in java web application using Jquery and JSON</h3>
    </div>
    <br />
    <br />
    <div class="search-container">
    	<div class="ui-widget">
    		<input type="text" id="search" name="search" class="search" />
    	</div>
    </div>
    </body>
    </html>
    

     

    Js file

     
    Here we get data from database via ajax and apply autocompleter
     

    $(document).ready(function() {
    	$(function() {
    		$("#search").autocomplete({
    		source : function(request, response) {
    		$.ajax({
    			url : "SearchController",
    			type : "GET",
    			data : {
    				term : request.term
    			},
    			dataType : "json",
    			success : function(data) {
    				response(data);
    			}
    		});
    	}
    });
    });
    });
    

     
    When a user types a character in text box ,jQuery will fire an ajax request to the controller, in this case controller is SearchController as mentioned in the above js file.
     

    Controller

     
    Creating The Controller To Handle Ajax Calls

    package com.servlet;
    
    import java.io.IOException;
    import java.util.ArrayList;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.dao.DataDao;
    import com.google.gson.Gson;
    
    public class Controller extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	protected void doGet(HttpServletRequest request,
    		HttpServletResponse response) throws ServletException, IOException {
    
    		response.setContentType("application/json");
    		try {
    			String term = request.getParameter("term");
    			System.out.println("Data from ajax call " + term);
    
    			DataDao dataDao = new DataDao();
    			ArrayList<String> list = dataDao.getFrameWork(term);
    
    			String searchList = new Gson().toJson(list);
    			response.getWriter().write(searchList);
    		} catch (Exception e) {
                            System.err.println(e.getMessage());
    		}
    	}
    }
    

     
    This servlet will call the business class which in turn creates the necessary connection and returns the data back as an array list to the controller. After getting the data we convert it to json format and return it back to the success function of our ajax call.
     

    Business class

    Creating Methods To Get Data From Database
     

    package com.dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.ArrayList;
    
    public class DataDao {
    	private Connection connection;
    
    	public DataDao() throws Exception {
    		connection = DBUtility.getConnection();
    	}
    
    	public ArrayList<String> getFrameWork(String frameWork) {
    	ArrayList<String> list = new ArrayList<String>();
    	PreparedStatement ps = null;
    	String data;
    	try {
    	ps = connection.prepareStatement("SELECT * FROM JAVA_FRAMEWORK  WHERE FRAMEWORK  LIKE ?");
    		ps.setString(1, frameWork + "%");
    		ResultSet rs = ps.executeQuery();
    		while (rs.next()) {
    			data = rs.getString("FRAMEWORK");
    			list.add(data);
    		}
    	} catch (Exception e) {
    		System.out.println(e.getMessage());
    	}
    	return list;
    }
    }
    

     

    Data Access object

     
    Connecting To Database Using JDBC

    package com.dao;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class DBUtility {
    	private static Connection connection = null;
    
    	public static Connection getConnection() throws Exception {
    		if (connection != null)
    			return connection;
    		else {
    			// Store the database URL in a string
    			String serverName = "127.0.0.1";
    			String portNumber = "1521";
    			String sid = "XE";
    			String dbUrl = "jdbc:oracle:thin:@" + serverName + ":" + portNumber
    					+ ":" + sid;
    			Class.forName("oracle.jdbc.driver.OracleDriver");
    
    			// set the url, username and password for the databse
    			connection = DriverManager.getConnection(dbUrl, "system", "admin");
    			return connection;
    		}
    	}
    }
    

     

    web.xml

     
    Make sure you have done servlet mapping properly in web.xml file. An example of this is given below,

    <welcome-file-list>
       <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
      <servlet-name>SearchController</servlet-name>
    <servlet-class>com.servlet.Controller</servlet-class>
    </servlet>
    <servlet-mapping>
      <servlet-name>SearchController</servlet-name>
      <url-pattern>/SearchController</url-pattern>
    </servlet-mapping>
    

     

    Demo

     
    Autocompleter in java
     

    dwd2
    Download It – jQueryAutocompleter.war

      Read More

    GridView in Struts2 using jQuery DataTable via Ajax

    Posted by in Ajax, jQuery, Struts-2 | 2 comments

     
    In this post, I am going to explain on how to use DataTable plugin to display data in Gridview format with pagination feature in Struts 2 web application.
     
    Gridview in Struts2 using jQuery DataTable plugin
     
    DataTable is a jQuery plugin which adds a lot of functionality to plain HTML tables, such as filtering, paging sorting, changing page length, server side processing etc.
     

    Library

    In this example, I am going to retrieve values from a csv file and display it in html table. For this, I am going to use OpenCSV library which simplifies the work of parsing CSV files. Here the Data table will load the data by making an Ajax call.
     
    Note:
    • Refer the article on how to Read / Write CSV file in Java using Opencsv library/ .
     
    Since the response to be generated from the action class is of type JSON, So to handle it you need struts2-json-plugin-2.x.x.jar. This plugin allows you to serialize the Action class attribute (which has getter and setter) into a JSON object. Refer this article here for more detail.
     
    Now create a dynamic web project in eclipse and create two folders named ‘js’ and ‘css’ under WebContent, and add the following javascript files from DataTable to the ‘js’ folder

    • jquery.dataTables.js
    • jquery.js

    Add the following css files from DataTable & jQuery ui to ‘css’ folder.

    • demo_page.css
    • demo_table_jui.css
    • jquery-ui-x.x.x.css
     
    ** UPDATE: Struts 2 Complete tutorial now available here.
     
    Download the csv file from which the data is to be read from here and place it under src folder, This files contains four columns – company, country, revenue, and year.
     

    Project Structure

     
    Folder structure - Gridview - Struts2 - DataTable 2
     

    Model class

     
    Create a model class that gets and sets the data from the four columns (company, country, revenue, and year) of the csv file.
     

    package com.model;
    
    public class RevenueReport {
    
    	public RevenueReport(String company, String country, String year,
    			String revenue) {
    		this.company = company;
    		this.country = country;
    		this.year = year;
    		this.revenue = revenue;
    	}
    
    	private String company;
    	private String country;
    	private String year;
    	private String revenue;
    
    	public String getCountry() {
    		return country;
    	}
    
    	public String getRevenue() {
    		return revenue;
    	}
    
    	public String getCompany() {
    		return company;
    	}
    
    	public String getYear() {
    		return year;
    	}
    
    	public void setCountry(String country) {
    		this.country = country;
    	}
    
    	public void setRevenue(String revenue) {
    		this.revenue = revenue;
    	}
    
    	public void setCompany(String company) {
    		this.company = company;
    	}
    
    	public void setYear(String year) {
    		this.year = year;
    	}
    }
    

     

    Business class

     
    Create a Business Service class that would fetch data from the csv file using model class.
     

    package com.service;
    
    import java.io.*;
    import java.io.InputStreamReader;
    import java.util.LinkedList;
    import java.util.List;
    
    import au.com.bytecode.opencsv.CSVReader;
    
    import com.model.RevenueReport;
    
    public class BusinessService {
    
    public static List<RevenueReport> getCompanyList() {
    
    	List<RevenueReport> listOfCompany = new LinkedList<RevenueReport>();
    	String fileName = "Company_Revenue.csv";
    
    	InputStream is = Thread.currentThread().getContextClassLoader()
    			.getResourceAsStream(fileName);
    	BufferedReader br = new BufferedReader(new InputStreamReader(is));
    
    	try {
    		CSVReader reader = new CSVReader(br);
    		String[] row = null;
    		while ((row = reader.readNext()) != null)
    		{
    		listOfCompany.add(new RevenueReport(row[0], row[1], row[2],	row[3]));
    		}
    		reader.close();
    	} catch (IOException e) {
    		System.err.println(e.getMessage());
    	}
    	return listOfCompany;
    }
    }
    

     

    Jsp

     
    Now create the jsp file to display the data fetched from csv file in html table and enhance the table features using DataTable plugin.
     

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>Gridview in Struts2 using jQuery DataTable plugin</title>
    
    <link href="css/demo_table_jui.css" rel="stylesheet" />
    <link href="css/jquery-ui.css" rel="stylesheet" />
    <link href="css/demo_page.css" rel="stylesheet" />
    
    <script src="js/jquery.js"></script>
    <script src="js/jquery.dataTables.js"></script>
    <script>
    $(document).ready(function() {
    	$(".jqueryDataTable").dataTable({
    		"sPaginationType" : "full_numbers",
    		"bProcessing" : false,
    		"bServerSide" : false,
    		"sAjaxSource" : "dataTablesAction",
    		"bJQueryUI" : true,
    		"aoColumns" : [
                { "mData": "company" },
                { "mData": "country" },
                { "mData": "year" },
                { "mData": "revenue" }
            ]
        } );
    } );
    </script>
    
    </head>
    
    <body id="dt_example">
    <div id="container">
    <h1>Ajax based Gridview in Struts2 using jQuery DataTable plugin</h1>
    <div id="demo_jui">
    	<table class="display jqueryDataTable">
    	<thead>
    	<tr>
    		<th>Company</th>
    		<th>Country</th>
    		<th>Year</th>
    		<th>Revenue</th>
    	</tr>
    	</thead>
    	<tbody>
    	</tbody>
    	</table>
    </div>
    </div>
    </body>
    </html>
    

     

    Action class

     
    In reply to each request for information that DataTables makes to the server, it expects to get a well formed JSON object with the parameter below.

    1. aaData- The data in a 2D array.
     

    package com.action;
    
    import java.util.List;
    
    import com.model.RevenueReport;
    import com.opensymphony.xwork2.Action;
    import com.service.BusinessService;
    
    public class GridViewAction implements Action {
    
    	private List<RevenueReport> aaData;
    
    	public List<RevenueReport> getAaData() {
    		return aaData;
    	}
    
    	public void setAaData(List<RevenueReport> aaData) {
    		this.aaData = aaData;
    	}
    
    	public String execute() {
    		aaData = BusinessService.getCompanyList();
    		return SUCCESS;
    	}
    }
    

     

    struts.xml

     

    <struts>
      	<package name="default" extends="json-default">
    		<action name="dataTablesAction" class="com.action.GridViewAction">
    			<result type="json">grid.jsp</result>
    		</action>
    	</package>
    	
    </struts>
    

    Note that I have extended “json-default” package instead of struts-default package and I have set the result type to json, I have explained about the reason for extending “json-default” package in the article AJAX implementation in Struts 2 using JQuery and JSON, please refer the mentioned link if you are not aware of the same.
     

    web.xml

     
    Make sure you have done servlet mapping properly in web.xml file as shown below

    <web-app>
    <display-name>Struts2</display-name>
    <filter>
    	<filter-name>struts2</filter-name>
    	<filter-class>
    	 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
            </filter-class>
    </filter>
    <filter-mapping>
    	<filter-name>struts2</filter-name>
    	<url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
    	<welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    </web-app>
    

     

    Demo

     
    Gridview in Struts2 using jQuery DataTable plugin
     


      Read More

    Ajax based Gridview in Java Web Applications using jQuery DataTable plugin

    Posted by in Ajax, J2EE, jQuery, Servlet

     
    In this post, I am going to explain on how to use DataTable plugin to display data in Gridview format in Java web application.
     
    Gridview in Java web application using jQuery DataTable plugin
     
    DataTable is a jQuery plugin which adds a lot of functionality to plain HTML tables, such as filtering, paging sorting, changing page length, server side processing etc.
     

    Library required

    In this example instead of using database, I am going to retrieve values from a csv file and display it in html table. For this, I am going to use OpenCSV library which simplifies the work of parsing CSV files. Here the Data table will load the data by making an Ajax call.
     
    Note:
    • Refer the article on how to Read / Write CSV file in Java using Opencsv library/ .
     
    Now create a dynamic web project in eclipse and create two folders named ‘js’ and ‘css’ under WebContent, and add the following javascript files from DataTable to the ‘js’ folder

    • jquery.dataTables.js
    • jquery.js

    Add the following css files from DataTable & jQuery ui to ‘css’ folder.

    • demo_page.css
    • demo_table_jui.css
    • jquery-ui-x.x.x.css
     
    Download the csv file from which the data is to be read from here and place it under src folder. This css files contains four columns of csv file – company, country, revenue, and year.
     

    Project Structure

     
    Folder structure - Gridview - Java - DataTable
     

    Model class

     
    Create a model class that gets and sets the data from the four columns (company, country, revenue, and year) of the csv file.
     

    package com.model;
    
    public class RevenueReport {
    
    	public RevenueReport(String company, String country, String year,
    			String revenue) {
    		this.company = company;
    		this.country = country;
    		this.year = year;
    		this.revenue = revenue;
    	}
    
    	private String company;
    	private String country;
    	private String year;
    	private String revenue;
    
    	public String getCountry() {
    		return country;
    	}
    
    	public String getRevenue() {
    		return revenue;
    	}
    
    	public String getCompany() {
    		return company;
    	}
    
    	public String getYear() {
    		return year;
    	}
    
    	public void setCountry(String country) {
    		this.country = country;
    	}
    
    	public void setRevenue(String revenue) {
    		this.revenue = revenue;
    	}
    
    	public void setCompany(String company) {
    		this.company = company;
    	}
    
    	public void setYear(String year) {
    		this.year = year;
    	}
    }
    

     

    Recommended reading:

     

    Business class

     
    Create a Business Service class that would fetch data from the csv file using model class.
     

    package com.service;
    
    import java.io.*;
    import java.io.InputStreamReader;
    import java.util.LinkedList;
    import java.util.List;
    
    import au.com.bytecode.opencsv.CSVReader;
    
    import com.model.RevenueReport;
    
    public class BusinessService {
    
    public static List<RevenueReport> getCompanyList() {
    
    	List<RevenueReport> listOfCompany = new LinkedList<RevenueReport>();
    	String fileName = "Company_Revenue.csv";
    
    	InputStream is = Thread.currentThread().getContextClassLoader()
    			.getResourceAsStream(fileName);
    	BufferedReader br = new BufferedReader(new InputStreamReader(is));
    
    	try {
    		CSVReader reader = new CSVReader(br);
    		String[] row = null;
    		while ((row = reader.readNext()) != null)
    		{
    		listOfCompany.add(new RevenueReport(row[0], row[1], row[2],	row[3]));
    		}
    		reader.close();
    	} catch (IOException e) {
    		System.err.println(e.getMessage());
    	}
    	return listOfCompany;
    }
    }
    

     

    Jsp

     
    Now create the jsp file to display the data fetched from csv file in html table and enhance the table features using DataTable plugin.
     

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>Gridview in Servlet using jQuery DataTable plugin</title>
    
    <link href="css/demo_table_jui.css" rel="stylesheet" />
    <link href="css/jquery-ui.css" rel="stylesheet" />
    <link href="css/demo_page.css" rel="stylesheet" />
    
    <script src="js/jquery.js"></script>
    <script src="js/jquery.dataTables.js"></script>
    <script>
    // Ajax call to Servlet to display data via DataTables
    $(document).ready(function() {
    	$(".jqueryDataTable").dataTable({
    		"sPaginationType" : "full_numbers",
    		"bProcessing" : false,
    		"bServerSide" : false,
    		"sAjaxSource" : "displayData",
    		"bJQueryUI" : true,
    		"aoColumns" : [
                { "mData": "company" },
                { "mData": "country" },
                { "mData": "year" },
                { "mData": "revenue" }
            ]
        } );
    } );
    </script>
    </head>
    
    <body id="dt_example">
    <div id="container">
    <h1>Ajax based Gridview using jQuery DataTable plugin</h1>
    <div id="demo_jui">
    	<table class="display jqueryDataTable">
    	<thead>
    	<tr>
    		<th>Company</th>
    		<th>Country</th>
    		<th>Year</th>
    		<th>Revenue</th>
    	</tr>
    	</thead>
    	<tbody>
    	</tbody>
    	</table>
    </div>
    </div>
    </body>
    </html>
    

     

    DataTable Parameters class

     
    In reply to each request for information that DataTables makes to the server, it expects to get a well formed JSON object with some parameters.So Create a DataTable Parameters class with all those required parameters
     

    package com.dataTable;
    
    import java.util.List;
    
    import com.model.RevenueReport;
    
    public class DataTableParameters {
    	// Data table plugin parameter
    	int iTotalRecords;
    	int iTotalDisplayRecords;
    	String sEcho;
    	String sColumns;
    	List<RevenueReport> aaData;
    
    	public int getiTotalRecords() {
    		return iTotalRecords;
    	}
    
    	public void setiTotalRecords(int iTotalRecords) {
    		this.iTotalRecords = iTotalRecords;
    	}
    
    	public int getiTotalDisplayRecords() {
    		return iTotalDisplayRecords;
    	}
    
    	public void setiTotalDisplayRecords(int iTotalDisplayRecords) {
    		this.iTotalDisplayRecords = iTotalDisplayRecords;
    	}
    
    	public String getsEcho() {
    		return sEcho;
    	}
    
    	public void setsEcho(String sEcho) {
    		this.sEcho = sEcho;
    	}
    
    	public String getsColumns() {
    		return sColumns;
    	}
    
    	public void setsColumns(String sColumns) {
    		this.sColumns = sColumns;
    	}
    
    	public List<RevenueReport> getAaData() {
    		return aaData;
    	}
    
    	public void setAaData(List<RevenueReport> aaData) {
    		this.aaData = aaData;
    	}
    }
    

     

    Servlet implementation

     

    package com.servlet;
    
    import java.io.IOException;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    import com.dataTable.DataTableParameters;
    import com.model.RevenueReport;
    import com.service.BusinessService;
    
    public class DataTableServlet extends HttpServlet {
    
    	private static final long serialVersionUID = 1L;
    
    	protected void doGet(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		response.setContentType("application/json");
    		// Call business service class to get list of company
    		List<RevenueReport> listOfCompany = BusinessService.getCompanyList();
    
    		DataTableParameters dataTableParam = new DataTableParameters();
    		//Set the list fetched in aaData
    		dataTableParam.setAaData(listOfCompany);
    
    	    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    	    //Convert Java Object to Json
    		String json = gson.toJson(dataTableParam);
    
    		response.getWriter().print(json);
    	}
    
    	protected void doPost(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		doGet(request, response);
    	}
    }
    

     

    web.xml

    Make sure you have done servlet mapping properly in web.xml file. An example of this is given below,
     

    <web-app>
    <servlet>
    	<display-name>displayData</display-name>
    	<servlet-name>displayData</servlet-name>
    	<servlet-class>com.servlet.DataTableServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>displayData</servlet-name>
    	<url-pattern>/displayData</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
    	<welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    </web-app>
    

     

    Demo

     
    Gridview in Java web application using jQuery DataTable plugin
     

    dwd2
    Download It – GridViewDataTable.war
    Read More
    Page 2 of 4112345...102030...Last»