因爲有個項目中須要用到數據顯示的表格插件,通過查閱資料發現了這款插件,在使用過程當中也遇到好的問題,不過都解決了,全部在閒暇時間把這款插件結合struts2 作一個demo給你們,但願對看到的人有所幫助。
javascript
文章中有什麼錯誤請指出,遇到問題也能夠留言。
css
轉發時候請說明一下,尊重個人勞動成果。謝謝!
html
官方網站:http://www.jtable.org/java
jTable是基於AJAX不要編碼HTML或者Javascript CRUD 表的的jQuery插件。mysql
Java Servlet demo : http://www.programming-free.com/search/label/jTablejquery
1.新建工程git
2.配置struts2環境web
將struts2的lib包放入工程中,配置 web.xml 文件, 寫struts.xml文件 。ajax
<?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> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <constant name="struts.custom.i18n.resources" value="message" /> <constant name="struts.i18n.encoding" value="utf-8" /> <!--必定要繼承 json-default--> <package name="student" extends="json-default" namespace="/student"> <action name="listStudentByPageAction" class="com.action.StudentAction" method="listStudentByPage"> <result type="json"></result> </action> <action name="getJSONResult" class="com.action.StudentAction" method="listStudentByPage"> <result type="json" /> </action> </package> </struts>
3.將jtable的相關文件放入工程中(文件可從官方網站下載)sql
項目源碼結構以下圖所示
1.student
package com.bean; 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; } }
2.StudentDao
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.bean.Student; import com.jdbc.DataAccessObject; public class StudentDao { private Connection dbConnection; private PreparedStatement pStmt; public StudentDao() { 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 int getCount() { String count = "SELECT COUNT(*) FROM STUDENT"; int i = 0; try { Statement st = dbConnection.createStatement(); ResultSet rs = st.executeQuery(count); if (rs.next()) { i = rs.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } return i; } public List<Student> getAllStudentsByPage(int startRow, int pageSize) { List<Student> students = new ArrayList<Student>(); String query = "SELECT * FROM STUDENT LIMIT ? OFFSET ?"; try { pStmt = dbConnection.prepareStatement(query); pStmt.setInt(1, pageSize); pStmt.setInt(2, startRow); ResultSet rs = pStmt.executeQuery(); // 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; } }
3.DataAccessObject
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 { // Store the database URL in a string String serverName = "localhost"; String portNumber = "3306"; String sid = "test"; String dbUrl = "jdbc:mysql://" + serverName + ":" + portNumber + "/" + sid; try { Class.forName("com.mysql.jdbc.Driver"); // set the url, username and password for the database connection = DriverManager.getConnection(dbUrl, "root", "root"); } catch (Exception e) { e.printStackTrace(); } return connection; } } }
4.StudentAcion
我只寫了一個加載列表的action 各位能夠按照個人方法依次編寫其餘函數
package com.action; import java.util.ArrayList; import java.util.List; import com.bean.Student; import com.dao.StudentDao; import com.opensymphony.xwork2.Action; public class StudentAction { // 屬性 private int studentId; private String name; private String department; private String emailId; private Student record; private List<Student> records; private String result; private String message; /** 分頁 **/ private int jtStartIndex; private int jtPageSize; private int totalRecordCount; private StudentDao dao; public StudentAction() { dao = new StudentDao(); } /** * 獲取列表 * * @return */ public String listStudentByPage() { records = new ArrayList<Student>(); try { records = dao.getAllStudentsByPage(jtStartIndex, jtPageSize); totalRecordCount = dao.getCount(); System.out.println(records.size()+"--"+totalRecordCount); result = "OK"; } catch (Exception e) { e.printStackTrace(); message = e.getMessage(); result = "ERROR"; } return Action.SUCCESS; } //省略 set get }
5.index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path; %> <title>Insert title here</title> <link type="text/css" rel="stylesheet" href="<%=basePath%>/res/plugins/jtable/themes/metro/blue/jtable.css" /> <link type="text/css" rel="stylesheet" href="<%=basePath%>/res/css/jquery-ui-1.10.3.custom.css" /> <script type="text/javascript" src="<%=basePath%>/res/plugins/jquery-1.9.0.min.js"></script> <script type="text/javascript" src="<%=basePath%>/res/plugins/jquery-ui-1.10.0.min.js"></script> <script type="text/javascript" src="<%=basePath%>/res/plugins/jtable/jquery.jtable.js"></script> </head> <body> <div style="width: 80%; margin-right: 10%; margin-left: 10%; text-align: center;"> <h4>AJAX based CRUD operations using jTable in J2EE</h4> <div id="StudentTableContainer"></div> </div> </body> <script type="text/javascript"> $(document).ready(function() { $('#StudentTableContainer').jtable({ title : 'Students List', paging: true, //Enable paging pageSize: 10, //Set page size (default: 10) actions : { listAction : '<%=basePath%>/student/listStudentByPageAction', createAction: '<%=basePath%>/student/insertStudentAction', 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> </html>
前面都是一些準備工做,即便各位按照個人步驟也必定不會運行成功,我在寫這個demo的時候已經測試過了。你們也許對其中一些變量名稱有疑問,請認真看下面的部分。
在StudentAction中有這七個變量
private Student record;//單條記錄,這個變量在添加信息時候使用, private List<Student> records;//數據列表, private String result;//結果標識 private String message;//信息標識(在程序出行錯誤時候,jtable會 alert出這個信息,全部通常攜帶異常信息) /** 分頁 **/ private int jtStartIndex;//分頁的開始位 private int jtPageSize;//頁面大小 private int totalRecordCount;//數據列表中的記錄數
上面的註釋中解釋了一部分,這些都是jtable要使用分頁功能時候必須的變量。
下面解釋爲何調試不出來的緣由:
請你們看看jtable.js源碼,我這裏爲你們複製一段
/* LOADING RECORDS *****************************************************/ /* Performs an AJAX call to reload data of the table. *************************************************************************/ _reloadTable: function (completeCallback) { var self = this; //Disable table since it's busy self._showBusy(self.options.messages.loadingMessage, self.options.loadingAnimationDelay); //Generate URL (with query string parameters) to load records var loadUrl = self._createRecordLoadUrl(); //Load data from server self._onLoadingRecords(); self._ajax({ url: loadUrl, data: self._lastPostData, success: function (data) { self._hideBusy(); //Show the error message if server returns error if (data.Result != 'OK') { self._showError(data.Message); return; } //Re-generate table rows self._removeAllRows('reloading'); self._addRecordsToTable(data.Records); self._onRecordsLoaded(data); //Call complete callback if (completeCallback) { completeCallback(); } }, error: function () { self._hideBusy(); self._showError(self.options.messages.serverCommunicationError); } }); },
這段代碼在jtable.js 390行開始。
這段代碼中清楚的寫道jtable加載數據的ajax函數,請仔細觀察其中的 Result、Message、Records這三個變量首字符全是大寫,而咱們的程序的變量是小寫。
也許有人會說我能夠把咱們的程序變量改成大寫啊,可是問題出現了:
第1、不符合java代碼編寫風格,
第2、根本調試不通,在action中變量的set和get方法的下一個字母的大寫,例如:
public Student getRecord() { return record; } public void setRecord(Student record) { this.record = record; }
若是你將變量的首字符設置爲大寫,set和get方法的下一個字母也是大寫,而struts2框架經過set和get獲取變量的時候默認將變量的首字符設置成小寫,因此你的首字母大寫的變量不會傳遞到前臺。(這部分應該是利用Java的反射機制,struts2並不知道你action中的私有變量,它是經過你公開的set和get方法獲取的到你的變量)
解決的辦法就是修改jtable.js的源碼,經過個人測試只需用將相應的ajax函數中的 data.Result、data.Records 等在獲取數據的地方修改便可,各位能夠從個人附件中直接下載使用。
須要修改的數據有:
data.Result(7處修改);
data.Message(7處修改);
data.record(5處);
data.Records(2處修改);
data.Options(1處修改);
data.TotalRecordCount(1處修改);
data.jtStartIndex(無需修改);
data.jtPageSize(無需修改);