JSP recorrido etiqueta personalizada

Crear una clase de controlador de etiquetas

package com.javaweb.tag;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class ForEach extends SimpleTagSupport {
	private Object items;
	private String var ;
	
	public void setItems(Object items) {
		this.items = items;
	}
	public void setVar(String var) {
		this.var = var;
	}
	public Collection getColl(){
		if(items instanceof List){
			return (List) items;
		}else if(items instanceof Set){
			return (Set) items;
		}else if(items instanceof Map){
			return ((Map) items).entrySet();
			//反射判断itmes对象是不是为基础数据类型的数组
		}else if(items.getClass().isArray()){
			List nums = new ArrayList<>();
			//遍历数组,反射获取数组长度
			for(int i=0;i<Array.getLength(nums);i++){
			//反射获取数组的值,添加到集合中
				nums.add(Array.get(items, i));
			}
			//返回集合
			return nums;
		}
		return null;
	}
	@Override
	public void doTag() throws JspException, IOException {
		for(Object obj: getColl()){
			//将obj以名为var值为obj设置到域中
			this.getJspContext().setAttribute(var, obj);
			//获取标签体中的内容到标准输出流中
			this.getJspBody().invoke(null);
		}
	}
	
	
}

etiqueta de registro

<?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">
	<tlib-version>1.0</tlib-version>
	<short-name>ct</short-name>
    <uri>http://myself/jsp/el/tag</uri>
    <tag>
        <name>forEach</name>
        <tag-class>com.javaweb.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>false</rtexprvalue>
        </attribute>
    </tag>
    
    
</taglib>

Utilice etiquetas

<% 
	List<String> names = new ArrayList<>();
	names.add("张三");
	names.add("隶属于");
	names.add("王五");
	pageContext.setAttribute("names", names);
%>
	<ct:forEach items="${names}" var="name">
		${name}<br/>
	</ct:forEach>
Publicados 114 artículos originales · ganado elogios 8 · vistas 5481

Supongo que te gusta

Origin blog.csdn.net/OVO_LQ_Start/article/details/104858107
Recomendado
Clasificación