本文示範如何在 ExtJS 的表格中實作分頁功能,並透過 JSP 與後端 Action 傳遞資料。以下依序說明前端、後端與相關配置。
前端 ExtJS 程式碼
透過 JsonStore 定義資料來源,並以 PagingToolbar 建立分頁工具列,最後用 GridPanel 呈現資料:
Ext.onReady(function() {
store3 = new Ext.data.JsonStore({
autoDestroy: true,
totalProperty: 'totle',
url: 'service.do',
storeId: 'myStore',
root: 'data',
fields: [ 'id', "name", "pw" ]
});
var pagingToolbar = new Ext.PagingToolbar({
emptyMsg: "沒有數據",
displayInfo: true,
displayMsg: "顯示從{0}條數據到{1}條數據,共{2}條數據",
store: store3,
pageSize: 50
});
var grade = new Ext.grid.GridPanel({
title: "數據列表",
store: store3,
height: 300,
bbar: pagingToolbar,
columns: [
{ header: "id", dataIndex: "id", width: 300 },
{ header: "name", dataIndex: "name", width: 300 },
{ header: "pw", dataIndex: "pw" }
],
region: 'center'
});
var panel = new Ext.Viewport({
layout: 'border',
items: [ grade ]
});
});
後端 Action
Action 負責產生資料、封裝成 JSON,並轉發到 info.jsp:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List list = new ArrayList();
for (int i = 0; i < 50; i++) {
Person p = new Person();
p.setId("id" + i);
p.setName("name" + i);
p.setPw("pw" + i);
list.add(p);
}
StringBuffer info = new StringBuffer();
info.append("{totle:2000,data:");
info.append(JSONArray.fromObject(list));
info.append("}");
System.out.println(info.toString());
request.setAttribute("info", info.toString());
request.getRequestDispatcher("/info.jsp").forward(request, response);
}
info.jsp(注意:除了 @page 不能有其他文字)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
${info}
web.xml 配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xmlns:web="https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>com.aa.TestAction</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
整體流程是:ExtJS 的 JsonStore 以 service.do 為資料來源,Action 產生資料後轉發到 info.jsp,再由 JSP 直接輸出 JSON 字串供前端解析。其中 info.jsp 需特別注意——除了 @page 頁面指令外不能有任何其它文字(包括空白與換行),否則會污染輸出的 JSON 而導致解析失敗。這正是使用 JSP 直接輸出 JSON 時最常見的陷阱。