EasyUI 是基於 jQuery 的經典 UI 框架,DataGrid 是其核心組件。本文詳細記錄 SSH(Struts2 + Spring + Hibernate)整合 EasyUI 實現 DataGrid 服務端分頁的完整流程,包含資料庫建表、後端分頁查詢、JSON 回傳、前端渲染全鏈路。
-- Oracle
CREATE TABLE STUDENT (
STUDENTID VARCHAR2(32) PRIMARY KEY,
NAME VARCHAR2(50),
GENDER VARCHAR2(10),
AGE VARCHAR2(10)
);
-- 插入測試資料(至少 6 筆驗證分頁)
INSERT INTO STUDENT VALUES ('1', '張三', '男', '20');
INSERT INTO STUDENT VALUES ('2', '李四', '女', '21');
-- ... 更多測試資料
src/ ├── com.model.Student -- 實體類 ├── com.model.Student.hbm.xml -- Hibernate 映射 ├── com.service.StudentService -- 服務介面 ├── com.serviceImpl.StudentServiceImpl ├── com.action.StudentAction -- Struts2 Action ├── applicationContext.xml ├── applicationContext_db.xml -- 數據源、SessionFactory、事務 ├── applicationContext_bean.xml -- Bean 註入 ├── struts.xml └── index.jsp
// Student.java
public class Student {
private String studentid;
private String name;
private String gender;
private String age;
// getter/setter 省略
}
// Student.hbm.xml
<class name="com.model.Student" table="STUDENT">
<id name="studentid" column="STUDENTID">
<generator class="assigned"/>
</id>
<property name="name" column="NAME"/>
<property name="gender" column="GENDER"/>
<property name="age" column="AGE"/>
</class>
// StudentService.java
public interface StudentService {
List getStudentList(String page, String rows) throws Exception;
int getStudentTotal() throws Exception;
}
// StudentServiceImpl.java
public class StudentServiceImpl implements StudentService {
private SessionFactory sessionFactory;
public List getStudentList(String page, String rows) {
int currentPage = Integer.parseInt((page == null || "0".equals(page)) ? "1" : page);
int pageSize = Integer.parseInt((rows == null || "0".equals(rows)) ? "10" : rows);
return sessionFactory.getCurrentSession()
.createQuery("from Student")
.setFirstResult((currentPage - 1) * pageSize)
.setMaxResults(pageSize)
.list();
}
public int getStudentTotal() {
return sessionFactory.getCurrentSession()
.createQuery("select count(*) from Student")
.uniqueResult(); // 比 .list().size() 效率高
}
// getter/setter
}
<!-- applicationContext_db.xml 關鍵片段 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>
<property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
<property name="user" value="username"/>
<property name="password" value="password"/>
<!-- 連線池調優參數 -->
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list><value>com/model/Student.hbm.xml</value></list>
</property>
<property name="hibernateProperties">
<props><prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop></props>
</property>
</bean>
<!-- 宣告式事務 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="servicePointcut" expression="execution(* com.serviceImpl..*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut"/>
</aop:config>
// StudentAction.java
public class StudentAction {
private StudentService studentService;
private String page, rows; // EasyUI 自動傳遞
public String getAllStudent() throws Exception {
List list = studentService.getStudentList(page, rows);
int total = studentService.getStudentTotal();
toJson(list, total);
return null; // 直接輸出 JSON,不跳轉視圖
}
private void toJson(List list, int total) throws IOException {
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
JSONObject json = new JSONObject();
json.put("total", total);
json.put("rows", list); // net.sf.json 自動序列化 List
response.getWriter().write(json.toString());
}
// getter/setter
}
<struts>
<package name="easyui" extends="json-default">
<action name="getAllStudentAction" class="student_action" method="getAllStudent">
<result type="json"/>
</action>
</package>
</struts>
需依賴 struts2-json-plugin,繼承 json-default 才能使用 type="json"。
<%@ page pageEncoding="UTF-8"%>
<% String path = request.getContextPath(); %>
<html>
<head>
<script src="<%=path%>/js/easyui/jquery-1.8.0.min.js"></script>
<script src="<%=path%>/js/easyui/jquery.easyui.min.js"></script>
<script src="<%=path%>/js/easyui/locale/easyui-lang-zh_CN.js"></script>
<link rel="stylesheet" href="<%=path%>/js/easyui/themes/default/easyui.css"/>
<link rel="stylesheet" href="<%=path%>/js/easyui/themes/icon.css"/>
</head>
<body>
<table id="mydatagrid">
<thead>
<tr>
<th data-options="field:'studentid',width:100,align:'center'">學號</th>
<th data-options="field:'name',width:100,align:'center'">姓名</th>
<th data-options="field:'gender',width:100,align:'center'">性別</th>
<th data-options="field:'age',width:100,align:'center'">年齡</th>
</tr>
</thead>
</table>
<script>
$(function() {
$('#mydatagrid').datagrid({
title: '學生資料',
iconCls: 'icon-ok',
width: 600,
url: 'getAllStudentAction.action',
pageSize: 5,
pageList: [5, 10, 15, 20],
nowrap: true,
striped: true,
collapsible: true,
fitColumns: true,
pagination: true,
rownumbers: true,
singleSelect: true,
loadMsg: '資料載入中...',
columns: [[
{field:'ck', checkbox:true} // 凍結列示例
]]
});
});
</script>
</body>
</html>
| 屬性 | 說明 |
|---|---|
| url | 請求資料的 Action 路徑,返回 {total: 100, rows: [...]} |
| pagination | true 啟用分頁工具欄 |
| pageSize | 預設每頁筆數 |
| pageList | 可切換的每頁筆數選單 |
| fitColumns | true 自適應父容器寬度 |
| rownumbers | true 顯示行號 |
| singleSelect | true 單選模式 |
response.setCharacterEncoding("UTF-8"),JSP 頁面 pageEncoding="UTF-8"。getStudentTotal() 是否正確返回,EasyUI 依賴 total 計算分頁。page、rows 參數名稱與 EasyUI 傳遞一致。OpenSessionInViewFilter 或 DTO 轉換。SSH 整合 EasyUI DataGrid 核心在於:後端返回 {total, rows} 結構 JSON、前端 DataGrid 配置 pagination 與 url。掌握此模式,可快速構建企業級列表頁面。後續可擴展增刪改查、批量操作、匯出 Excel 等功能。