日期:2014-05-16 浏览次数:20361 次
1. 开发遍历所有类型数据的标签
标签处理类: package com.csdn.web.example; import java.io.IOException; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; publicclass ForEachAll extends SimpleTagSupport{ private Collection collection; private String var; private Object items; publicvoid setVar(String var) { this.var = var; } publicvoid setItems(Object items) { this.items = items; } @Override publicvoid doTag() throws JspException, IOException { //判断是否是Map 下面的三个判断可以在doTage()方法中也可以在setItems()方法中 if(itemsinstanceof Map){ //这里要把jsp页面传进来的属性强转为Map类型,不能new HashMap Map map = (Map) items; collection = map.entrySet(); } //判断是否是set、list if(itemsinstanceof Collection){ collection = (Collection) items; } //判断是否是数组,各种数组 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)); } } Iterator it = collection.iterator(); while(it.hasNext()){ Object obj = it.next(); this.getJspContext().setAttribute(var,obj); this.getJspBody().invoke(null); } } } Jsp文件 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="example" prefix="example"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>遍历各种类型数据</title> </head> <body> <% List list = new ArrayList(); list.add(1); list.add("aa"); list.add("bb"); list.add(2); request.setAttribute("list",list); %> <example:forEachAll var="str" items="${list}"> ${ str }<br> </example:forEachAll> <hr> <% Map map = new HashMap(); map.put("1","aa"); map.put(2,"aa"); map.put(3,"aa"); map.put(4,"aa"); request.setAttribute("map",map); %> <example:forEachAll items="${map}" var="map"> ${ map.key}-------${ map.value }<br> </example:forEachAll> <hr> <% String[] strs = {"asd","fff","v","tt"}; request.setAttribute("strs",strs); %> <example:forEachAll items="${strs}" var="str">${str}<br></example:forEachAll> <hr> <% int[] i = {1,2,3,4}; request.setAttribute("i",i); %> <example:forEachAll items="${i}" var="num">${num}<br> </example:forEachAll> </body> </html> 注:描述文件与前面博客的forEach标签的定义一样,这里就不啰嗦的列出,不懂的可以去看上一篇博客 2. 开发html转义标签案例分析: 标签处理类: package com.csdn.web.example; import java.io.IOException; import java.io.StringWriter; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.JspFragment; import javax.servlet.jsp.tagext.SimpleTagSupport; publicclass HtmlFilter extends SimpleTagSupport { @Override publicvoid doTag() throws JspException, IOE