基於 JSP 2.0+ SimpleTagSupport 開發自訂標籤,示範「重複輸出標籤體」、「帶屬性迴圈」、「內容轉大寫」、「HTML 轉義」四種常見模式。
public class SimpleDemo1 extends SimpleTagSupport {
@Override
public void doTag() throws JspException, IOException {
JspFragment js = this.getJspBody();
js.invoke(null); // 直接輸出到 response
}
}
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);
}
}
}
<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>
<hbsi:demo counts="3">aaaaaaa<br/></hbsi:demo> <!-- 輸出三次 -->
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);
}
}
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);
}
}
}
<c:forEach2 var="str" items="${map}">${str.key}-----${str.value}<br/></c:forEach2>
<c:forEach2 var="str" items="${strs}">${str}<br></c:forEach2>
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> <!-- 輸出原始碼而非超連結 -->