Pagination in Java Web Applications using jQuery jTable plugin
In the previous article “Setting up JQuery jTable plugin in Java Web Applications” I have explained how to setup jTable plugin in Java web application and in the article “Ajax based CRUD operation in Java Web Applications using JQuery jTables plugin” I have implemented Ajax based CRUD operation using JTable plugin.
This is the third article on jQuery jTable plugin in java web application that describes on how to implement pagination feature to do server side paging and it will not explain how to setup jTable plugin in java web application here. So If you have not read the previous articles “Setting up JQuery jTable plugin in Java web application” and “Ajax based curd operation in Java web application using JQuery jTables plugin”, I will recommend that you read that article first because first one explains how you can integrate the JTable plug-in with a Java web application and in second article explains on how to implement ajax based curd operation using jTable plugin. This article will assume that the code for the integration of the jQuery JTable plug-in is implemented, and only the code required for implementing pagination in Java web application using jTable will be explained here.
Setup
As described above, the prerequisite for this code is that you integrate the jQuery jTable plugin into the Java web application. You can find detailed instructions at JQuery jTable plugin in Java web application, so now I am going to take the sample application I created for explaining AJAX based crud operations in jTable plugin and continue to implement paging for that application.
1. Download sample application from here and import the project in eclipse.
2. Follow the steps in this article here to create table in database and make sure you have atleast 5 records in the table.
Now on running this application in Tomcat Server, you will see a table displaying records without pagination such as the one shown below.
Steps to Enable Paging:
Changes from the browser perspective: jTable
To enable paging, paging option must set to true. You can also set pageSize option (default value is 10) in jQuery Script code.
$('#StudentTableContainer').jtable({ //... paging: true, //Set paging enabled pageSize: 3, //Set page size actions: { //... }, fields: { //... } });
Note: pageSize sets the initial number of records to be displayed per page.
Modified Jsp page is shown below
<!DOCTYPE html> <html> <head> <title>Pagination in Java Web Applications using jTable plugin</title> <!-- Include one of jTable 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" /> <!-- Include jTable script file. --> <!-- Include 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> <script type="text/javascript"> $(document).ready(function() { $('#StudentTableContainer').jtable({ title : 'Students List', paging: true, //Enable paging pageSize: 3, //Set page size (default: 10) actions: { listAction: 'Controller?action=list', createAction:'Controller?action=create', updateAction: 'Controller?action=update', deleteAction: 'Controller?action=delete' }, fields : { studentId : { title : 'Student Id', sort :true, 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'); }); </script> </head> <body> <div style="text-align: center;"> <h4>Pagination in Java Web Applications jTable</h4> <div id="StudentTableContainer"></div> </div> </body> </html>
Changes from the server’s perspective: Servlet
If paging is enabled in jsp then jTable sends two query string parameters to the server on listAction AJAX call:
• jtStartIndex: Start index of records for current page.
• jtPageSize: Count of maximum expected records.
And it expects additional information from server:
• TotalRecordCount: Total count of records.
In our previous example the url specified in the ‘listAction‘ option has business logic to fetch all records from database. Now in order to handle pagination this ‘listAction’ option should return only the part of resultset for each page, So handle this there are two changes that has to be done in the server side .
1. In order to return only a subset of records according to the page offset (jtStartIndex and jtPageSize), sql query used in CRUDDao should be modified with query below,
In case of Oracle database:
“SELECT * from (Select M.*, Rownum R from STUDENT M) where r > ” + < jtStartIndex> +” and r <= "+< jtStartIndex + jtPageSize >;
In case of MySql database:
select * from STUDENT limit <jtStartIndex>,<jtPageSize>
Changes made in CRUDDao at getAllStudents function
public List<Student> getAllStudents(int startPageIndex, int recordsPerPage) { List<Student> students = new ArrayList<Student>(); int range = startPageIndex+recordsPerPage; String query="SELECT * from (Select M.*, Rownum R From STUDENT M) where r > " + startPageIndex +" and r <= "+range; System.out.println(query); 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; }
2. As mentioned above, jTable need TotalRecordCount to be present in the json response, For which add the following function in CRUDDao which returns total Record Count value present in database.
public int getStudentCount() { int count=0; try { Statement stmt = dbConnection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) AS COUNT FROM STUDENT"); while (rs.next()) { count=rs.getInt("COUNT"); } } catch (SQLException e) { System.err.println(e.getMessage()); } return count; }
Changes made in Controller
Now open ‘CRUDContoller.java’ file and replace the logic inside the if loop -> ‘if(action.equals(“list”))’ with the below code,
if(action.equals("list")) { try { // Fetch Data from User Table int startPageIndex = Integer.parseInt(request.getParameter("jtStartIndex")); int recordsPerPage = Integer.parseInt(request.getParameter("jtPageSize")); // Fetch Data from Student Table studentList = dao.getAllStudents(startPageIndex, recordsPerPage); // Get Total Record Count for Pagination int userCount = dao.getStudentCount(); // Convert Java Object to Json String jsonArray = gson.toJson(studentList); // Return Json in the format required by jTable plugin jsonArray = "{\"Result\":\"OK\",\"Records\":" + jsonArray + ",\"TotalRecordCount\":" + userCount + "}"; response.getWriter().print(jsonArray); } catch(Exception ex){ String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getMessage()+"}"; response.getWriter().print(error); } }
Now on running the application, with the above changes, the final demo looks as shown below:
|
Read More
Pagination in Struts 2 using jQuery jTable plugin
In the previous article “Setting up JQuery jTable plugin in Struts 2″ I have explained how to setup jTable plugin in struts 2 and in the article “Ajax based curd operation in Struts 2 using JQuery jTables plugin” I have implemented Ajax based curd operation using JTable plugin.
This is the third article on jQuery jTable plugin in Struts 2 that describes on how to implement pagination feature to do server side paging in struts 2 using the JQuery jTable plugin and it will not explain how to setup jTable plugin in struts 2 here. So If you have not read the previous articles “Setting up JQuery jTable plugin in Struts 2″ and “Ajax based curd operation in Struts 2 using JQuery jTables plugin”, I will recommend that you read that article first because first one explains how you can integrate the JTable plug-in with a Struts 2 application and in second article explains on how to implement ajax based curd operation using jTable plugin. This article will assume that the code for the integration of the jQuery JTable plug-in is implemented, and only the code required for implementing pagination in Struts 2 using jTable will be explained here.
Setup
As described above, the prerequisite for this code is that you integrate the jQuery jTable plugin into the Struts 2. You can find detailed instructions here, at JQuery jTable plugin in Struts 2, so now I am going to take the sample application I created for explaining AJAX based crud operations in jTable plugin and continue to implement paging for that application.
1. Download sample application from here and import the project in eclipse
2. Follow the steps in this article here to create table in database.
Steps to enable Paging:
From the browser perspective: jTable
To enable paging, paging option must set to true. You can also set pageSize option (default value is 10) in jQuery Script code.
$('#StudentTableContainer').jtable({ //... paging: true, //Set paging enabled pageSize: 3, //Set page size actions: { //... }, fields: { //... } });
Note: pageSize sets the initial number of records to be displayed per page.
Modified Jsp page
<!DOCTYPE html> <html> <head> <title>jTable Pagination in Java Web Applications</title> <!-- Include one of jTable 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" /> <!-- Include 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> <script type="text/javascript"> $(document).ready(function() { $('#StudentTableContainer').jtable({ title : 'Students List', paging : true, //Enable paging pageSize : 3, //Set page size (default: 10) 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'); }); </script> </head> <body> <div style="text-align: center;"> <h3>jTable Pagination in Java Web Applications</h3> <div id="StudentTableContainer"></div> </div> </body> </html>
From the server’s perspective: Servlet
If paging is enabled, jTable sends two query string parameters to the server on listAction AJAX call:
• jtStartIndex: Start index of records for current page.
• jtPageSize: Count of maximum expected records.
And it expects additional information from server:
• TotalRecordCount: Total count of records.
In our previous example the url specified in the ‘listAction‘ option has business logic to fetch all records from database. Now in order to handle pagination this ‘listAction’ option should fetch only a part of records for each page, So handle this there are two changes that has to be done in the server side .
1. Modify oracle query to fetch only a subset of records based on the jtStartIndex and jtPageSize.
Since these values are sent along with the request as string parameters by jTable so add following member variable in struts 2 action class and create getters and setters for the same
// Holds Start Page Index private int jtStartIndex; // Hold records to be displayed per Page private int jtPageSize;
2. As mentioned above, jTable need TotalRecordCount to be present in the json response, For which add a member variable totalRecordCount in struts 2 action class and create getters and setters for the same.
Now replace the list method in action class with the below code,
public String list() { try { // Fetch Data from Student Table records = dao.getAllStudents(jtStartIndex, jtPageSize); // Get Total Record Count for Pagination totalRecordCount = dao.getStudentCount(); result = "OK"; } catch (Exception e) { result = "ERROR"; message = e.getMessage(); } return Action.SUCCESS; }
Changes made at Dao class
Add below two methods in ‘CrudDao.java’ file
1. Method to get the count of total number of records in the result set.
public int getStudentCount() { int count=0; try { Statement stmt = dbConnection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) AS COUNT FROM STUDENT"); while (rs.next()) { count=rs.getInt("COUNT"); } } catch (SQLException e) { System.err.println(e.getMessage()); } return count; }
2. In order to return only a subset of records according to the page offset (jtStartIndex and jtPageSize), oracle query should be modified as follows,
In case of Oracle database:
“SELECT * from (Select M.*, Rownum R from STUDENT M) where r > ” + < jtStartIndex> +” and r <= "+< jtStartIndex + jtPageSize >;
In case of MySql database:
select * from STUDENT limit <jtStartIndex>,<jtPageSize>
Now modify getAllUsers in CurdDao.java using below code
public List<Student> getAllStudents(int startPageIndex, int recordsPerPage) { List<Student> students = new ArrayList<Student>(); int range = startPageIndex+recordsPerPage; String query="SELECT * from (Select M.*, Rownum R From STUDENT M) where r > " + startPageIndex +" and r <= "+range; 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; }
This function returns only a subset of records according to the page offset (jtStartIndex and jtPageSize).
Now on running the application, with the above changes, the final demo looks as shown below:
|
Read More
Tab Style Login and Signup example using jQuery in Java web application
In this post, I am going to describe on how to design tab style login and registration panel using jquery ui tabs in java web applications. Here I’m using oracle database as a back end for registering and authenticating users.
Libraries required for the setup,
Now create a dynamic web project in eclipse and create two folders under WebContent and name it as ‘js’ and ‘css’. And add the downloaded jQuery javascript and css files to it. The final project structure will be as shown below
Now create a user table in Oracle database using the query below.
CREATE TABLE users (name VARCHAR (50), email VARCHAR (50), password VARCHAR (50), gender VARCHAR (50))
Jsp page
<!DOCTYPE html> <html> <head> <title>Login and registration</title> <link rel="stylesheet" href="css/jquery-ui.css"> <link rel="stylesheet" href="css/style.css"> <script src="js/jquery-1.11.1.js"></script> <script src="js/jquery-ui.js"></script> <script> $(function() { $( "#tabs" ).tabs(); }); </script> </head> <body> <div class="wrapper"> <div class="container"> <div id="tabs"> <ul> <li><a href="#login">Login</a></li> <li><a href="#register">Sign up</a></li> </ul> <div id="login"> <% if("Invalid Email or password".equals((String)session.getAttribute("error"))){ %> <h6> Invalid Email or password. Please try again.</h6> <%} %> <form method="post" action="LoginController"> <label for="email">Email:</label> <br/> <input type="text" name="email" id="email"/> <br/> <label for="password">Password:</label> <br/> <input type="password" name="password" id="password" /> <br/> <br/> <input type="submit" value="Login"> </form> </div> <div id="register"> <form method="post" action="RegistrationController"> <label for="fullname">Name:</label><br/> <input type="text" name="fullname" id="fullname" /> <br/> <label for="email">Email:</label><br/> <input type="text" name="email" id="email" /> <br/> <label for="password">Password:</label><br/> <input type="password" name="password" id="password" /> <br/> <label for="gender">Gender:</label><br/> <select name="gender" id="gender"> <option value="Male">Male</option> <option value="Female">Female</option> </select> <br/> <br/> <input type="submit" value="Register"> </form> </div> </div> </div> </div> </body> </html>
User defined CSS
body { background-color: #e6e6e6; font-family: Helvetica; font-size: 17px; color: #666; margin: 0px; padding: 0px; } .wrapper { width: 1024px; height: 650px; margin: 0 auto; background: white; margin: 0 auto; } .container { min-height: 400px; border-top: 1px solid gray; padding: 50px; }
Recommended reading :
Controller
File: LoginController.java
LoginController doPost method gets triggered on clicking Login button and its doGet Method gets triggered on clicking logout
package com.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.dao.UserDAO; public class LoginController extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String error; String email = request.getParameter("email"); String password = request.getParameter("password"); HttpSession session = request.getSession(); UserDAO userDAO = new UserDAO(); String userName = userDAO.verifyUser(email, password); if (userName == null) { error = "Invalid Email or password"; session.setAttribute("error", error); response.sendRedirect("index.jsp"); } else { session.setAttribute("user", userName); response.sendRedirect("welcome.jsp"); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if ("logout".equalsIgnoreCase(request.getParameter("param"))) { HttpSession session = request.getSession(); session.removeAttribute("user"); session.invalidate(); response.sendRedirect("index.jsp"); } } }
SignupController
This controller gets triggred on clicking Register button under Signup tab
package com.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.dao.UserDAO; public class SignupController extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("fullname"); String email = request.getParameter("email"); String password = request.getParameter("password"); String gender = request.getParameter("gender"); UserDAO userDAO = new UserDAO(); int result = userDAO.createUser(name, email, password, gender); if (result == 1) { response.sendRedirect("success.jsp"); } } }
Also read :
UserDAO
Create a class that performs registration and authentication operation in database
package com.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import com.jdbc.DBUtility; public class UserDAO { private Connection dbConnection; private PreparedStatement pStmt; private String SQL_SELECT = "SELECT name FROM users WHERE email = ? AND password = ?"; private String SQL_INSERT = "INSERT INTO users (name,email,password,gender) VALUES (?,?,?,?)"; public UserDAO() { dbConnection = DBUtility.getConnection(); } public String verifyUser(String email, String password) { String userName = null; try { pStmt = dbConnection.prepareStatement(SQL_SELECT); pStmt.setString(1, email); pStmt.setString(2, password); ResultSet rs = pStmt.executeQuery(); while (rs.next()) { userName = rs.getString("name"); } } catch (Exception e) { System.err.println(e.getMessage()); } return userName; } public int createUser(String name, String email, String password, String gender) { int result = 0; try { pStmt = dbConnection.prepareStatement(SQL_INSERT); pStmt.setString(1, name); pStmt.setString(2, email); pStmt.setString(3, password); pStmt.setString(4, gender); result = pStmt.executeUpdate(); } catch (Exception e) { System.err.println(e.getMessage()); } return result; } }
DBUtility
Next let us create a utility class to handle connections to database.
package com.jdbc; import java.sql.Connection; import java.sql.DriverManager; public class DBUtility { private static Connection connection = null; public static Connection getConnection() { if (connection != null) return connection; else { // database URL String dbUrl = "jdbc:oracle:thin:@localhost:1521:XE"; try { Class.forName("oracle.jdbc.driver.OracleDriver"); // set the url, username and password for the database connection = DriverManager.getConnection(dbUrl, "system", "admin"); } catch (Exception e) { e.printStackTrace(); } return connection; } } }
In addition to above files there are 2 other jsp pages,
1. welcome.jsp page which get displayed when the user logged into the application.
2. Success.jsp page which gets displayed once user registration is successful.
I have not showcased up these files here, you may download the files to see complete example.
Note: Since this article is intended to demonstrate the usage of tabs feature in jquery, so I have not included any validation parts in it.
Demo
On running the application
On clicking Signup tab
|
Read More
CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax
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,
- jQuery
- jQuery UI
- jTable
- struts2-json-plugin-2.x.x.jar
- Commonly required Struts 2 jars
Create a dynamic project in eclipse and setup above required libraries as explained here. The final project structure of this looks as below.
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:
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
On clicking ‘Add new record’
Now the new record will be added with fade out animation
On clicking edit button
On clicking delete button
In the next article Pagination in Struts 2 using jQuery jTable plugin I have implemented paging feature in the CRUD example.
|
Reference
Read MoreAutocomplete in Struts 2 using Jquery and JSON via Ajax
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.
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
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 :
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 :
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
|
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
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.
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
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
|
Read More