日期:2014-05-16  浏览次数:20349 次

jsp自定义标签库实现数据列表显示

文章标题: jsp自定义标签库实现数据列表显示

作者: javaboy2012
Email:yanek@163.com
qq:    1046011462

 

1. 定义标签库类 UserListTag.java

package com.yanek.cms.tag;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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

import com.yanek.cms.vo.UserInfo;

public class UserListTag extends BodyTagSupport {

 private String name;// 一个属性名
 private Iterator it;// 要迭代的对象
 private int cateid; // 用户类别id

 @Override
 public int doEndTag() throws JspException {
  try {
   if (bodyContent != null) {
    bodyContent.writeOut(bodyContent.getEnclosingWriter());
   }
  } catch (IOException e) {
   e.printStackTrace();

  }
  return EVAL_PAGE;
 }

 @Override
 public int doStartTag() throws JspException {

  //这里根据用户类型,构造不同的列表数据,实现可以根据数据库获取
  List<UserInfo> users = new ArrayList<UserInfo>();
  if (cateid == 1) {
   users.add(new UserInfo("张三", 20, "Zhangsan@163.com"));

   users.add(new UserInfo("李四", 30, "Lisi@sina.com"));
  } else {
   users.add(new UserInfo("王五", 33, "Wangwu@qq.com"));
   users.add(new UserInfo("赵六", 33, "zhaoliu@qq.com"));
  }
  it = users.iterator();

  if (it == null) {
   return SKIP_BODY;

  } else {
   return continueNext();
  }
 }

 private int continueNext() {
  if (it.hasNext()) {
   pageContext.setAttribute(name, it.next(), pageContext.PAGE_SCOPE);
   return EVAL_BODY_TAG;
  } else {

   return SKIP_BODY;
  }
 }

 @Override
 public int doAfterBody() {
  return continueNext();
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getCateid() {
  return cateid;
 }

 public void setCateid(int cateid) {
  this.cateid = cateid;
 }

}

 

 


2. 在WEB-INF目录下 新建标签库描述文件my_cms_tag.tld:

my_cms_tag.tld 

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.0</jspversion>
<shortname>cms</shortname>
<uri>http://www.58tech.cn/mystruts/tags-cms</uri>

<!-- userListTag start -->

    <tag>

       <name>userListTag</name>

       <tag-class>com.yanek.cms.tag.UserListTag</tag-class>

   
       <body-content>jsp</body-content>
   
      <variable>
        <!--<name-given>user_info</name-given>-->
        <name-from-attribute>name</name-