萬盛學電腦網

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

JSP 自訂標籤 forEach 遍歷集合與 HTML 轉義實作

延續上篇,完整實作支援 Map、Collection、陣列的 <c:forEach2> 標籤,以及將標籤體內容進行 HTML 轉義的 <c:htmlFilter> 標籤。

1. 通用集合迴圈標籤

標籤處理器

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);
        }
    }
}

TLD 定義

<tag>
  <name>forEach2</name>
  <tag-class>com.csdn.items.ForEachTag2</tag-class>
  <body-content>scriptless</body-content>
  <attribute><name>var</name><required>true</required></attribute>
  <attribute><name>items</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute>
</tag>

JSP 使用

<% Map map = new HashMap(); map.put("aa","aaaa"); ... request.setAttribute("map",map); %>
<c:forEach2 var="str" items="${map}">${str.key}-----${str.value}<br/></c:forEach2>

<% String[] strs = {"aa","bb","cc"}; request.setAttribute("strs",strs); %>
<c:forEach2 var="str" items="${strs}">${str}<br></c:forEach2>

2. HTML 轉義標籤

標籤處理器

public class HTMLFilter extends SimpleTagSupport {
    @Override
    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();
    }
}

TLD 定義

<tag>
  <name>htmlFilter</name>
  <tag-class>com.csdn.items.HTMLFilter</tag-class>
  <body-content>scriptless</body-content>
</tag>

使用效果

<c:htmlFilter><a href=""> aaa</a></c:htmlFilter>
<!-- 頁面顯示:<a href=""> aaa</a> -->
copyright © 萬盛學電腦網 all rights reserved