JSP自定义标签

1、自定义标签语言特点

<开始标签 属性="属性值">标签体</结束标签>

空标签
                 <br/><hr/>

<开始标签></结束标签>
<开始标签/>


2. 自定义标签的开发及使用步骤

2.1 创建一个标签助手类(继承BodyTagSupport)

标签属性必须助手类的属性对应、且要提供对应get/set方法rtexprvalue

2.2 创建标签库描述文件(tld),添加自定义标签的配置

注:tld文件必须保存到WEB-INF目录或其子目录

2.3 在JSP通过taglib指令导入标签库,并通过指定后缀
访问自定义标签

3、JSP自定义标签生命周期图:

                                                                                                                                


                                                        SKIP_BODY:跳过主体
                              EVAL_BODY_INCLUDE:计算标签主体内容并[输出]
                              EVAL_BODY_BUFFERED:计算标签主体内容并[缓存]
                              EVAL_PAGE:计算页面的后续部分
                                SKIP_PAGE:跳过页面的后续部分
                              EVAL_BODY_AGAIN:再计算主体一次

4、自定义set跟out标签

分别创建一个set和out助手类

  4、1:set助手类

package com.zl.jsp;
/*
 * set助手类
 */
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport; 

public class SetTag extends BodyTagSupport{

	private static final long serialVersionUID = 1L;

	private String var;
	private Object value;
	public String getVar() {
		return var;
	}
	public void setVar(String var) {
		this.var = var;
	}
	public Object getValue() {
		return value;
	}
	public void setValue(Object value) {
		this.value = value;
	}
	
	@Override
	public int doStartTag() throws JspException {
		pageContext.setAttribute(var, value);//将值存入pageContext
		return SKIP_BODY;
	}
}


 

   4、2:out助手类

package com.zl.jsp;
/*
 * out助手类
 */
import java.io.IOException;

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

public class OutTag extends BodyTagSupport {

	
	public Object getValue() {
		return value;
	}
	public void setValue(Object value) {
		this.value = value;
	}
	private Object value;
	@Override
	public int doStartTag() throws JspException {
		 JspWriter out=pageContext.getOut();
		 try {
			out.write(value.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
		return SKIP_BODY;
	}
	
	
}

 

  4、3:set跟out的tld文件

 <!-- OUT标签 -->
  <tag>
     <name>out</name>
     <tag-class>com.zl.jsp.OutTag</tag-class>
     <body-content>empty</body-content>
  <attribute>
      <name>value</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
  </attribute>
  </tag>
  
  
     <!-- SET标签 -->
  <tag>
    <name>set</name>
    <tag-class>com.zl.jsp.SetTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
       <name>var</name>
       <required>false</required>
       <rtexprvalue>true</rtexprvalue>
    </attribute>
     <attribute>
       <name>value</name>
       <required>true</required>
       <rtexprvalue>true</rtexprvalue>
    </attribute>
    </tag>
  

  

  4、4:jsp页面演示set与out标签

 <!-- set标签 -->
<!-- OUT标签 -->
        <c:set var="name" value="hello" ></c:set>





 
        <c:out value="${name }"/>

  

  

5、自定义if标签

  5、1:if助手类

package com.zl.jsp;
/*
 * if助手类
 */
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class IfTag extends BodyTagSupport{
  private boolean test;

public boolean isTest() {
	return test;
}

public void setTest(boolean test) {
	this.test = test;
}
  
   @Override
	public int doStartTag() throws JspException {
		if(!test) {
			return SKIP_BODY;//不显示标签中间的内容
		}
		return EVAL_BODY_INCLUDE;//显示标签中间的内容
	}


	
	
	
}

    

  5.2:if标签的tld文件

 <!-- if标签 -->
  <tag>
    <name>if</name>
    <tag-class>com.zl.jsp.IfTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
       <name>test</name>
       <required>true</required>
       <rtexprvalue>true</rtexprvalue>
    </attribute>
    </tag>
  
  

  

  5、3:jsp页面演示if标签

   <!-- if标签 -->
   <c:if test="true" >zs</c:if>
   <c:if test="false">ls</c:if>

  

6、自定义Foreach标签

  6、1:Foreach助手类

package com.zl.jsp;
/*
 * Foreach助手类
 */
import java.util.Iterator;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.swing.text.html.HTML.Tag;

public class ForEachTag extends BodyTagSupport{
    
	//集合
	private List<Object> items;
	//变量的名称
     private String var;
	public List<Object> getItems() {
		return items;
	}
	public void setItems(List<Object> items) {
		this.items = items;
	}
	public String getVar() {
		return var;
	}
	public void setVar(String var) {
		this.var = var;
	}
     
	
     @Override
    public int doStartTag() throws JspException {
    	// TODO Auto-generated method stub
    	 if(items==null||items.size()==0) {
    		 return SKIP_BODY;
    	 }
    	 else {
    		 Iterator<Object> i=items.iterator();
    		 pageContext.setAttribute("s", i);
    		 //第一次给变量进行赋值
    	     pageContext.setAttribute(var, i.next());
    	return EVAL_BODY_INCLUDE;
      } 
    	 }
     
     @Override
    public int doAfterBody() throws JspException {
    	 Iterator<Object> it=(Iterator<Object>)pageContext.getAttribute("s");
     while(it.hasNext()) {
    	 //如何将循环读取出来的数据,显示在页面上
    	 pageContext.setAttribute(var, it.next());
    	 return EVAL_BODY_AGAIN;
     }
    	
    	return SKIP_BODY;
    }
     
   
 
}

  6、2:Foreach标签的tld文件

   
 <!--foreach标签  -->
<tag>
 <name>foreach</name>
 <tag-class>com.zl.jsp.ForEachTag</tag-class>
 <body-content>JSP</body-content>
 <attribute>
 <name>items</name>
 <required>true</required>
 <rtexprvalue>false</rtexprvalue>
 </attribute>
 
 <attribute>
 <name>var</name>
 <required>true</required>
 <rtexprvalue>true</rtexprvalue>
 </attribute>
</tag>

  

  6、3:jsp页面演示Foreach标签

<%
   List list=new ArrayList();
   list.add(new Student("sb1","zs"));
   list.add(new Student("sb2","ls"));
   list.add(new Student("sb3","ws"));
   request.setAttribute("stus",list);

%>
<p:foreach items="${stus }" var="stu">
${stu.sid },${stu.sname }<br>
</p:foreach>

  

7、自定义select标签

  7、1:select标签助手类

private static final long serialVersionUID = 1L;
    private String id;
    private String name;
    private List<Object> items = new ArrayList<Object>();
    private String textKey;
    private String textval;
    private String headTextKey;
    private String headTextVal;
    private String selectedval;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public List<Object> getItems() {
        return items;
    }

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

    public String getTextKey() {
        return textKey;
    }

    public void setTextKey(String textKey) {
        this.textKey = textKey;
    }

    public String getTextval() {
        return textval;
    }

    public void setTextval(String textval) {
        this.textval = textval;
    }

    public String getHeadTextKey() {
        return headTextKey;
    }

    public void setHeadTextKey(String headTextKey) {
        this.headTextKey = headTextKey;
    }

    public String getHeadTextVal() {
        return headTextVal;
    }

    public void setHeadTextVal(String headTextVal) {
        this.headTextVal = headTextVal;
    }

    public String getSelectedval() {
        return selectedval;
    }

    public void setSelectedval(String selectedval) {
        this.selectedval = selectedval;
    }

    @Override
    public int doStartTag() throws JspException {
        JspWriter out = pageContext.getOut();
        try {
            out.write(toHTML());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return super.doStartTag();
    }

    /**
     * 拼接出下拉列表所对应的select的html代码 
     * <select id='' name=''>
     *  <option value='-1'selected>=======请选择======</option>
     *   </select>
     */
    private String toHTML() throws Exception {
        StringBuilder sb = new StringBuilder();
        sb.append("<select id='" + id + "' name='" + name + "'>");
        if (headTextKey == null || "".equals(headTextKey) || headTextVal == null || "".equals(headTextVal)) {
            sb.append("<option value='" + headTextKey + "' selected>" + headTextVal + "</option>");
        }
        String val;
        String html;
        for (Object obj : items) {
            // 要让学生的id存入数据库,让学生的名字展示在jsp页面
            // <option value='s001'>ls</option>
            // obj sid sname
            Field textKeyField = obj.getClass().getDeclaredField(textKey);
            textKeyField.setAccessible(true);
            val = (String) textKeyField.get(obj);
            html = BeanUtils.getProperty(obj, textval);
            if(val.equals(selectedval)) {
                sb.append(" <option value='"+val+"'selected>"+html+"</option>");
            }else {
                sb.append("<option value='"+val+"'>"+html+"</option>");
            }
        }
        sb.append("</select>");
        return sb.toString();
}

  

  7、2:select的tld文件

  
<!--select标签  -->


<tag> <name>select</name> <tag-class>com.jsp.ServletTag</tag-class> <body-content>JSP</body-content> <attribute> <name>id</name> <required>false</required> <rtexprvalue>flase</rtexprvalue> </attribute> <attribute> <name>name</name> <required>flase</required> <rtexprvalue>flase</rtexprvalue> </attribute> <attribute> <name>items</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>textKey</name> <required>true</required> <rtexprvalue>false</rtexprvalue> </attribute> <attribute> <name>textval</name> <required>true</required> <rtexprvalue>flase</rtexprvalue> </attribute> <attribute> <name>headTextKey</name> <required>false</required> <rtexprvalue>false</rtexprvalue> </attribute> <attribute> <name>headTextVal</name> <required>false</required> <rtexprvalue>flase</rtexprvalue> </attribute> <attribute> <name>selectedval</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag>

  

   7、3:jsp页面演示select标签

<p:select  items="${stus }" textval="sname" textKey="sid"></p:select>
<p:select headTextKey="-1" headTextVal="===请选择学生===" items="${stus }" textval="sname" textKey="sid"></p:select>

  

 

原文地址:https://www.cnblogs.com/BAYOUA/p/11046809.html