萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

表格點擊表頭排序功能實現:前後端協作完整方案

需求分析

使用者點擊表格表頭欄位,該欄位在升序/降序間切換;其他欄位恢復預設升序。需前端記錄狀態、後端動態構建 SQL ORDER BY 子句。

前端實現策略

HTML 結構

<table id="dataTable">
    <thead>
        <tr>
            <th data-col="id">ID <span class="sort-icon">⇅</span></th>
            <th data-col="name">名稱 <span class="sort-icon">⇅</span></th>
            <th data-col="price">價格 <span class="sort-icon">⇅</span></th>
            <th data-col="created_at">建立時間 <span class="sort-icon">⇅</span></th>
        </tr>
    </thead>
    <tbody><!-- 資料列由後端渲染或 AJAX 載入 --></tbody>
</table>

jQuery 互動邏輯

<script>
$(function() {
    let currentSortCol = null;
    let currentSortDir = 'asc'; // asc / desc
    
    $('#dataTable th[data-col]').click(function() {
        const col = $(this).data('col');
        const $icon = $(this).find('.sort-icon');
        
        // 切換排序方向
        if (col === currentSortCol) {
            currentSortDir = (currentSortDir === 'asc') ? 'desc' : 'asc';
        } else {
            currentSortCol = col;
            currentSortDir = 'asc';
        }
        
        // 更新圖示
        $('#dataTable .sort-icon').text('⇅');
        $icon.text(currentSortDir === 'asc' ? '↑' : '↓');
        
        // 重新載入資料 (AJAX 方式)
        loadTableData(currentSortCol, currentSortDir);
        
        // 或表單提交方式 (傳統)
        // $('#sortCol').val(currentSortCol);
        // $('#sortDir').val(currentSortDir);
        // $('#searchForm').submit();
    });
    
    function loadTableData(sortCol, sortDir) {
        $.get('dataList.jsp', { sortCol, sortDir }, function(html) {
            $('#dataTable tbody').html(html);
        });
    }
});
</script>

後端 JSP/Servlet 處理

接收參數並構建 SQL

<%@ page import="java.sql.*, javax.sql.DataSource" %>
<%
    String sortCol = request.getParameter("sortCol");
    String sortDir = request.getParameter("sortDir");
    
    // 白名單驗證:防止 SQL 注入
    Set allowedCols = Set.of("id", "name", "price", "created_at");
    if (sortCol == null || !allowedCols.contains(sortCol)) {
        sortCol = "id";        // 預設排序欄位
        sortDir = "asc";
    }
    if (!"asc".equalsIgnoreCase(sortDir) && !"desc".equalsIgnoreCase(sortDir)) {
        sortDir = "asc";
    }
    
    String orderBy = " ORDER BY " + sortCol + " " + sortDir.toUpperCase();
    
    // 執行查詢
    String sql = "SELECT id, name, price, created_at FROM products" + orderBy;
    // ... 執行查詢並輸出 tbody 列
%>

BIRT 報表整合範例 (原文場景)


// BIRT reportContext 中的 initialize() 腳本
dataSetName = "fundcatagoryseasontemplate";
sortCol = reportContext.getHttpServletRequest().getParameter("sortCol");
sortDir = reportContext.getHttpServletRequest().getParameter("sortDir");
currentURL = reportContext.getHttpServletRequest().getRequestURL() 
           + "?" + reportContext.getHttpServletRequest().getQueryString();

if (sortDir != null) {
    sortDir = sortDir.contains("ASC") ? "DESC" : "ASC";
} else {
    sortDir = "ASC";
}

sortClause = "";
if (sortCol != null && !sortCol.isEmpty()) {
    sortClause = " ORDER BY " + sortCol + " " + sortDir;
}

// 修改資料集 SQL
reportContext.getReportRunnable()
    .getDesignInstance()
    .getDataSet(dataSetName)
    .queryText += sortClause;

// 重構目標 URL 供下次點擊使用
if (currentURL.contains("__sorting=")) {
    targetURL = currentURL.substring(0, currentURL.indexOf("__sorting") - 1);
} else {
    targetURL = currentURL;
}
targetURL += "&__sorting=true&sortDir=" + sortDir + "&sortCol=" + sortCol;

隱藏域儲存狀態 (傳統表單提交)

<form id="searchForm" action="list.jsp" method="get">
    <input type="hidden" name="sortCol" id="sortCol" value="<%=sortCol%>">
    <input type="hidden" name="sortDir" id="sortDir" value="<%=sortDir%>">
    <!-- 其他搜尋條件 -->
</form>

進階優化

1. 多欄位排序


// 前端維護陣列 [{col:'name', dir:'asc'}, {col:'price', dir:'desc'}]
// 後端構建: ORDER BY name ASC, price DESC

2. 客戶端排序 (資料量小 < 1000 筆)

// 使用 DataTables.js 或 sorttable.js
$('#dataTable').DataTable({
    ordering: true,
    serverSide: false // 客戶端排序
});

3. 狀態持久化

// 儲存至 localStorage
localStorage.setItem('tableSort_' + tableId, JSON.stringify({col, dir}));
// 頁面載入時還原

安全性檢查清單

  • ✅ **欄位白名單驗證** - 絕不直接拼接使用者輸入到 SQL
  • ✅ **方向值白名單** - 僅允許 ASC/DESC
  • ✅ **使用 PreparedStatement** - 參數化查詢 (排序欄位無法參數化,故需白名單)
  • ✅ **大小寫正規化** - 統一轉大寫再拼接

總結

表格排序核心在於:**前端維護排序狀態 (欄位+方向) → 透過參數傳遞 → 後端白名單驗證後動態構建 ORDER BY**。AJAX 方式體驗更佳,傳統表單提交相容性更好。BIRT 等報表工具同理,在初始化腳本中修改資料集 SQL 實現。務必嚴格驗證輸入防止 SQL 注入。

copyright © 萬盛學電腦網 all rights reserved