萬盛學電腦網

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

JSP 自訂標籤開發:if/else 條件與集合迴圈完整範例

基於 JSP 2.0+ SimpleTagSupport 開發自訂標籤,示範「重複輸出標籤體」、「帶屬性迴圈」、「內容轉大寫」、「HTML 轉義」四種常見模式。

1. 簡單輸出標籤體

public class SimpleDemo1 extends SimpleTagSupport {
    @Override
    public void doTag() throws JspException, IOException {
        JspFragment js = this.getJspBody();
        js.invoke(null);  // 直接輸出到 response
    }
}

2. 帶屬性迴圈輸出

public class SimpleDemo2 extends SimpleTagSupport {
    private int counts;
    public void setCounts(int counts) { this.counts = counts; }

    @Override
    public void doTag() throws JspException, IOException {
        JspFragment js = this.getJspBody();
        for (int i = 0; i < counts; i++) {
            js.invoke(null);
        }
    }
}

TLD 定義

<tag>
  <name>demo</name>
  <tag-class>com.csdn.simple.SimpleDemo2</tag-class>
  <body-content>scriptless</body-content>
  <attribute>
    <name>counts</name>
    <required>true</required>
    <rtexprvalue>true</rtexprvalue>
  </attribute>
</tag>

JSP 使用

<hbsi:demo counts="3">aaaaaaa<br/></hbsi:demo>
<!-- 輸出三次 -->

3. 內容轉大寫(捕獲標籤體字串處理)

public void doTag() throws JspException, IOException {
    JspFragment js = this.getJspBody();
    StringWriter sw = new StringWriter();
    js.invoke(sw);                    // 寫入 StringWriter
    String s = sw.toString().toUpperCase();
    JspWriter out = this.getJspContext().getOut();
    for (int i = 0; i < counts2; i++) {
        out.print(s);
    }
}

4. 集合迴圈標籤(支援 Map/Collection/Array)

public class ForEachTag2 extends SimpleTagSupport {
    private String var;
    private Object items;
    private Collection collection;

    public void setVar(String var) { this.var = var; }
    public void setItems(Object items) {
        this.items = items;
        if (items instanceof Map) {
            collection = ((Map)items).entrySet();
        } else if (items instanceof Collection) {
            collection = (Collection) items;
        } else if (items.getClass().isArray()) {
            collection = new ArrayList();
            int len = Array.getLength(items);
            for (int i = 0; i < len; i++) collection.add(Array.get(items, i));
        }
    }

    @Override
    public void doTag() throws JspException, IOException {
        Iterator it = collection.iterator();
        while (it.hasNext()) {
            Object obj = it.next();
            this.getJspContext().setAttribute(var, obj);
            this.getJspBody().invoke(null);
        }
    }
}

JSP 使用範例

<c:forEach2 var="str" items="${map}">${str.key}-----${str.value}<br/></c:forEach2>
<c:forEach2 var="str" items="${strs}">${str}<br></c:forEach2>

5. HTML 轉義標籤(防 XSS)

public void doTag() throws JspException, IOException {
    JspFragment jf = this.getJspBody();
    StringWriter sw = new StringWriter();
    jf.invoke(sw);
    String s = filter(sw.toString());  // 轉義
    this.getJspContext().getOut().write(s);
}

private String filter(String msg) {
    if (msg == null) return null;
    StringBuffer sb = new StringBuffer(msg.length() + 50);
    for (char c : msg.toCharArray()) {
        switch (c) {
            case '<': sb.append("<"); break;
            case '>': sb.append(">"); break;
            case '&': sb.append("&"); break;
            case '"': sb.append("""); break;
            default: sb.append(c);
        }
    }
    return sb.toString();
}

使用

<c:htmlFilter><a href=""> aaa</a></c:htmlFilter>
<!-- 輸出原始碼而非超連結 -->
copyright © 萬盛學電腦網 all rights reserved