首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

SSH 整合 EasyUI 實現 DataGrid 分頁顯示完整教程

     編輯:Java 相關知識

前言

EasyUI 是基於 jQuery 的經典 UI 框架,DataGrid 是其核心組件。本文詳細記錄 SSH(Struts2 + Spring + Hibernate)整合 EasyUI 實現 DataGrid 服務端分頁的完整流程,包含資料庫建表、後端分頁查詢、JSON 回傳、前端渲染全鏈路。

一、技術棧與版本

  • Struts 2.3.x + Spring 3.2.x + Hibernate 3.6.x
  • EasyUI 1.3.2 + jQuery 1.8.0
  • Oracle 11g / MySQL 5.7

二、資料庫準備

-- 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

四、核心代碼實現

1. 實體類與映射

// 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>

2. 服務層:分頁查詢邏輯

// 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
}

3. Spring 配置:數據源與事務

<!-- 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>

4. Action:返回 EasyUI 要求的 JSON 格式

// 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
}

5. Struts 配置:JSON 插件

<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"。

6. JSP 頁面:DataGrid 初始化

<%@ 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>

五、EasyUI DataGrid 關鍵屬性解析

屬性說明
url請求資料的 Action 路徑,返回 {total: 100, rows: [...]}
paginationtrue 啟用分頁工具欄
pageSize預設每頁筆數
pageList可切換的每頁筆數選單
fitColumnstrue 自適應父容器寬度
rownumberstrue 顯示行號
singleSelecttrue 單選模式

六、常見坑點與解決

  • JSON 亂碼:Action 中設置 response.setCharacterEncoding("UTF-8"),JSP 頁面 pageEncoding="UTF-8"。
  • 總筆數為 0:檢查 getStudentTotal() 是否正確返回,EasyUI 依賴 total 計算分頁。
  • 分頁不生效:確認 Action 接收 page、rows 參數名稱與 EasyUI 傳遞一致。
  • Hibernate 懶加載異常:JSON 序列化觸發懶加載,配置 OpenSessionInViewFilter 或 DTO 轉換。

七、總結

SSH 整合 EasyUI DataGrid 核心在於:後端返回 {total, rows} 結構 JSON、前端 DataGrid 配置 pagination 與 url。掌握此模式,可快速構建企業級列表頁面。後續可擴展增刪改查、批量操作、匯出 Excel 等功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved