萬盛學電腦網

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

JSP 自定義標籤實現數據字典下拉框:Select、Options、Display 三標籤協作模式

需求背景

企業應用中大量下拉框數據來自「數據字典」(如:性別、訂單狀態、支付方式)。期望 JSP 頁面只需聲明:

<dict:select name="gender" dictCode="GENDER" value="${user.gender}"/>
自動渲染:<select name="gender"><option value="M" selected>男</option><option value="F">女</option></select>

架構設計:三標籤協作

標籤名職責對應類
select渲染 <select> 容器,管理 name、style、事件等屬性SelectTag
options遍歷字典集合,渲染 <option> 列表,支持 selected 判斷OptionsTag
selectDisplay純顯示模式:根據 value 反查 label,不渲染下拉框SelectDisplayTag

1. TLD 定義 /WEB-INF/tlds/dict.tld

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" 
        xmlns="https://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="https://java.sun.com/xml/ns/javaee web-jsptaglibrary_2_1.xsd">
    
    <tlib-version>1.0</tlib-version>
    <short-name>dict</short-name>
    <uri>https://example.com/tags/dict</uri>
    
    <tag>
        <name>select</name>
        <tag-class>com.example.tag.dict.SelectTag</tag-class>
        <body-content>JSP</body-content> <!-- 允許嵌套標籤 -->
        <attribute><name>name</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute>
        <attribute><name>dictCode</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute>
        <attribute><name>style</name><rtexprvalue>true</rtexprvalue></attribute>
        <attribute><name>onchange</name><rtexprvalue>true</rtexprvalue></attribute>
    </tag>
    
    <tag>
        <name>options</name>
        <tag-class>com.example.tag.dict.OptionsTag</tag-class>
        <body-content>empty</body-content>
        <attribute><name>collection</name><required>true</required><rtexprvalue>true</rtexprvalue><type>java.util.List</type></attribute>
        <attribute><name>valueField</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute>
        <attribute><name>labelField</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute>
        <attribute><name>selectedValue</name><rtexprvalue>true</rtexprvalue></attribute>
    </tag>
    
    <tag>
        <name>selectDisplay</name>
        <tag-class>com.example.tag.dict.SelectDisplayTag</tag-class>
        <body-content>empty</body-content>
        <attribute><name>collection</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute>
        <attribute><name>name</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute>
        <attribute><name>value</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute>
    </tag>
</taglib>

2. 核心實現類

SelectTag:容器標籤,暴露字典數據給子標籤

package com.example.tag.dict;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class SelectTag extends TagSupport {
    private String name;
    private String dictCode;
    private String style;
    private String onchange;
    
    // 字典服務 (實際應從 Spring 容器獲取,此處簡化)
    private DictService dictService = DictService.getInstance();

    @Override
    public int doStartTag() throws JspException {
        try {
            // 1. 根據 dictCode 獲取字典數據
            List> dictList = dictService.getDict(dictCode);
            
            // 2. 將數據放入 pageContext,供嵌套的 options 標籤使用
            pageContext.setAttribute("__dict_data_" + name, dictList);
            
            // 3. 輸出 select 開始標籤
            JspWriter out = pageContext.getOut();
            out.print("<select name=\"" + escapeHtml(name) + "\"");
            if (style != null) out.print(" style=\"" + escapeHtml(style) + "\"");
            if (onchange != null) out.print(" onchange=\"" + escapeHtml(onchange) + "\"");
            out.print(">");
            
        } catch (Exception e) {
            throw new JspException("SelectTag 初始化失敗", e);
        }
        return EVAL_BODY_INCLUDE; // 執行 Body (包含 options 標籤)
    }

    @Override
    public int doEndTag() throws JspException {
        try {
            pageContext.getOut().print("</select>");
            pageContext.removeAttribute("__dict_data_" + name); // 清理
        } catch (IOException e) {
            throw new JspException(e);
        }
        return EVAL_PAGE;
    }

    // Getter/Setter 省略...
    private String escapeHtml(String s) { /* 同上 */ }
}

OptionsTag:渲染選項列表

public class OptionsTag extends TagSupport {
    private List> collection;
    private String valueField;
    private String labelField;
    private Object selectedValue;

    @Override
    public int doStartTag() throws JspException {
        // 1. 獲取父標籤 SelectTag 存入的數據 (若未顯式傳入 collection)
        if (collection == null) {
            Tag parent = getParent();
            if (parent instanceof SelectTag) {
                String name = ((SelectTag) parent).getName();
                collection = (List) pageContext.getAttribute("__dict_data_" + name);
            }
        }
        
        if (collection == null) return SKIP_BODY;
        
        try {
            JspWriter out = pageContext.getOut();
            String selVal = selectedValue == null ? "" : selectedValue.toString();
            
            for (Map item : collection) {
                String val = String.valueOf(item.get(valueField));
                String label = String.valueOf(item.get(labelField));
                boolean selected = selVal.equals(val);
                
                out.print("<option value=\"" + escapeHtml(val) + "\"");
                if (selected) out.print(" selected");
                out.print(">" + escapeHtml(label) + "</option>");
            }
        } catch (IOException e) {
            throw new JspException(e);
        }
        return SKIP_BODY;
    }
    // Getter/Setter...
}

SelectDisplayTag:只讀顯示模式

public class SelectDisplayTag extends TagSupport {
    private List> collection;
    private String name;   // 僅作為標識
    private Object value;  // 要顯示的值

    @Override
    public int doStartTag() throws JspException {
        if (collection == null || value == null) return SKIP_BODY;
        
        try {
            String valStr = value.toString();
            String label = valStr; // 默認顯示值本身
            
            for (Map item : collection) {
                if (valStr.equals(String.valueOf(item.get("value")))) { // 約定鍵名
                    label = String.valueOf(item.get("label"));
                    break;
                }
            }
            
            pageContext.getOut().print("<span class='dict-display'>" + escapeHtml(label) + "</span>");
        } catch (IOException e) {
            throw new JspException(e);
        }
        return SKIP_BODY;
    }
    // Getter/Setter...
}

3. 字典服務與緩存 (簡化版)

public class DictService {
    private static DictService instance = new DictService();
    private Map>> cache = new ConcurrentHashMap<>();
    
    public static DictService getInstance() { return instance; }
    
    public List> getDict(String code) {
        return cache.computeIfAbsent(code, this::loadFromDb);
    }
    
    private List> loadFromDb(String code) {
        // 實際從數據庫查詢: SELECT code, value, label FROM sys_dict WHERE dict_code=?
        // 返回 List>
        return List.of(
            Map.of("value", "M", "label", "男"),
            Map.of("value", "F", "label", "女")
        );
    }
}

4. JSP 頁面使用示例

<%@ taglib prefix="dict" uri="https://example.com/tags/dict" %>

<!-- 編輯頁:下拉選擇 -->
<dict:select name="user.gender" dictCode="GENDER" value="${user.gender}" style="width:200px"/>

<!-- 列表頁:只讀顯示 -->
<dict:selectDisplay name="user.gender" dictCode="GENDER" value="${user.gender}"/>

<!-- 手動指定選項 (不走字典服務) -->
<dict:select name="priority" style="width:150px">
    <dict:options collection="${priorityList}" valueField="code" labelField="name" selectedValue="${task.priority}"/>
</dict:select>

優化與擴展方向

  • Spring 整合:標籤類實現 ApplicationContextAware,從容器獲取 DictService Bean
  • 緩存刷新:@Scheduled 定時刷新 / 配置中心推送 / 管理後台手動刷新
  • 國際化:label 支持 i18n Key,運行時根據 Locale 解析
  • 樹形字典:擴展 OptionsTag 支持遞歸渲染 <optgroup>
  • 前端組件化:配合 Select2/Element UI 等組件,標籤輸出 JSON 數據源
copyright © 萬盛學電腦網 all rights reserved