您的位置:首页 > Web前端 > JavaScript

实现 jstl标签foreach 功能

2016-01-06 22:13 597 查看
jsp 页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/includes/ctx.jsp" %>
<%@ taglib uri="/RemoveListItems" prefix="z"%>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>角色管理</title>
</head>
<body>
<z:for items="${rolelist}" var="z">
<p>${z.rolename}</p>
</z:for>
</body>
</html>


WEB-INF 目录下创建tld 文件

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee">
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>eRedLab JSPTag Library</shortname>
<uri>/RemoveListItems</uri>
<info>自定义标签</info>

<tag>
<name>for</name>
<tagclass>com.oa.tag.Repeater</tagclass>
<bodycontent>scriptless</bodycontent>
<info></info>
<attribute>
<name>items</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>var</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>index</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>


java 类代码

import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class Repeater extends TagSupport {

/**
*
*/
private static final long serialVersionUID = 4086401651029717288L;
private List<?> items;
private String var;
private String index;
private int i;

@Override
public int doStartTag() throws JspException {

if (items == null || items.size() == 0){
return SKIP_BODY;
}
if(index==null)index = "";

i = 0;
if(i<items.size()){
pageContext.setAttribute(var, items.get(i));
pageContext.setAttribute(index, i);
}

return EVAL_BODY_INCLUDE;
}

@Override
public int doAfterBody() throws JspException {
i++;
if(i < items.size()){
pageContext.setAttribute(var, items.get(i));
pageContext.setAttribute(index, i);
return EVAL_BODY_AGAIN;
}

return SKIP_BODY;
}

@Override
public int doEndTag() throws JspException {
return EVAL_PAGE;
}

public void setItems(List<?> items) {
this.items = items;
}

public void setVar(String var) {
this.var = var;
}

public void setIndex(String index){
this.index = index;
}

}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: