本节讲述自定义标签的用法。
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
package net.wanho.tag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
import java.util.Collection;
public class ForEach extends SimpleTagSupport {
private Collection<?> items;
public void setItems(Collection<?> items) {
this.items = items;
}
private String var;
public void setVar(String var) {
this.var = var;
}
@Override
public void doTag() throws JspException, IOException {
if (items != null) {
for (Object obj : items) {
getJspContext().setAttribute(var, obj);
getJspBody().invoke(null);
}
}
}
}
package net.wanho.tag;
import java.io.Serializable;
public class Student implements Serializable {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public Student() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>MyTag 1.2 core library</description>
<display-name>MyTag core</display-name>
<tlib-version>1.2</tlib-version>
<short-name>mytag</short-name>
<uri>http://tag.com/mytag/core</uri>
<tag>
<name>forEach</name>
<tag-class>net.wanho.tag.ForEach</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>items</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>var</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
<%@ page import="net.wanho.tag.Student" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="tag" uri="http://tag.com/mytag/core" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
List<Student> tg = new ArrayList<Student>();
tg.add(new Student(1, "AAA"));
tg.add(new Student(2, "BBB"));
tg.add(new Student(3, "CCC"));
tg.add(new Student(4, "DDD"));
request.setAttribute("tg", tg);
%>
<!-- 使用标签库foreach -->
<c:forEach items="${requestScope.tg}" var="abc">
${abc.id}--${abc.name}<br>
</c:forEach>
<!-- 使用自定义标签foreach -->
<tag:forEach items="${requestScope.tg }" var="abc">
${abc.id}--${abc.name}<br>
</tag:forEach>
</body>
</html>
原文:https://www.cnblogs.com/alichengxuyuan/p/12622664.html