天天看点

jsp自定义标签2·

jsp标签分为 UI标签,控制标签,数据标签

UI标签:用于jsp页面展示,不需要写标签的标签体

控制标签:有标签体,但是打印与否有属性值控制

数据标签:作用是存储数据,它既没有标签体,有没有在页面上展示任何内容

jsp自定义标签库也是有生命周期的,作用域仅在于当前page

jsp自定义标签2·

首先要自定义一个标签库的话,需要一个c.tld文件,所以拿一个列子来看下

下面

我只截取了一个属性,后面我还定义了很多属性,if,foreach,set,out,select

<?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">
    
  <description>zking 1.1 core library</description>
  <display-name>zking core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>c</short-name>
  <uri>/zking</uri>

  <tag>
    <description>
   
    </description>
    <!-- 标签库的标签名 -->
    <name>demo</name>
    <!-- 便签对应的助手类的全路径名 -->
    <tag-class>com.zking.jsp.day01.DemoTag</tag-class>
    
    <body-content>JSP</body-content>
    <attribute>
        <description>

        </description>
        <!-- 属性名 -->
        <name>test</name>
        <!-- 属性值是否必填 -->
        <required>false</required>
        <!-- 是否支持表达式  也就是是否可以使用${}  false的话只能填字符串  -->
        <rtexprvalue>false</rtexprvalue>
    </attribute>
  </tag>
  
           

UI标签:

out标签只有一个标签,所以就只定义一个属性

package com.zking.jsp2;

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{

	private static final long serialVersionUID = 8655118409172739205L;
	
	private Object value;

	public Object getValue() {
		return value;
	}

	public void setValue(Object value) {
		this.value = value;
	}
	
	@Override
	public int doStartTag() throws JspException {
		JspWriter out = pageContext.getOut();
		try {
			out.print(value);//输出值
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SKIP_BODY;
	}
	
}

           

下面就是select标签,也是外面开发中经常用到的一个标签

public class SelectTag extends BodyTagSupport{


	private static final long serialVersionUID = 5375902073989817712L;
	
	private String id;
	private String name;
	private List<Object> items=new ArrayList<>();
	private String textKey;  
	private String textVal;
	private String selectedVal;
	private String headerTextKey;
	private String headerTextVal;
	
	@Override 
	public int doStartTag() throws JspException {
		JspWriter out = pageContext.getOut();
		try {
			try {
				out.print(toHTML());
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return super.doStartTag();
	}
	
	private String toHTML() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		StringBuffer sb=new StringBuffer();
		sb.append("<select id='"+id+"' name='"+name+"'>");
		if(!(headerTextKey==null)||"".equals(headerTextKey)||
				headerTextVal==null||"".equals(headerTextVal)) {
			sb.append("<option selected value='"+headerTextVal+"'>"+headerTextKey+"</option>");
		}
		String value;
		String html;
		for (Object o : items) {
			Field field = o.getClass().getDeclaredField(textKey);
			field.setAccessible(true);
			value=(String)field.get(o);
			html=(String) PropertyUtils.getProperty(o, textVal);
			sb.append("<option value='"+value+"'>"+html+"</option>");
		}
		sb.append("</select>");
		return sb.toString();
	}

	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 getSelectedVal() {
		return selectedVal;
	}
	public void setSelectedVal(String selectedVal) {
		this.selectedVal = selectedVal;
	}
	public String getHeaderTextKey() {
		return headerTextKey;
	}
	public void setHeaderTextKey(String headerTextKey) {
		this.headerTextKey = headerTextKey;
	}
	public String getHeaderTextVal() {
		return headerTextVal;
	}
	public void setHeaderTextVal(String headerTextVal) {
		this.headerTextVal = headerTextVal;
	}
	public static long getSerialversionuid() {
		return serialVersionUID;
	}
           

控制标签

if 标签

public class IfTag extends BodyTagSupport {

	private static final long serialVersionUID = -8477321984637500253L;
	
	private boolean test;

	public boolean isTest() {
		return test;
	}

	public void setTest(boolean test) {
		this.test = test;
	}
	
	@Override
	public int doStartTag() throws JspException {
		// TODO Auto-generated method stub
		return test? EVAL_BODY_INCLUDE:SKIP_BODY;
	}
}
           

foreach标签

public class ForeachTag extends BodyTagSupport {

	private static final long serialVersionUID = -2643407962233076616L;
	
	private String var;
	private List<Object> items = new ArrayList<>();
	public String getVar() {
		return var;
	}
	public void setVar(String var) {
		this.var = var;
	}
	public List<Object> getItems() {
		return items;
	}
	public void setItems(List<Object> items) {
		this.items = items;
	}
	
	/**
	 *执行完这个方法的时候,var所代表的指针一定要向下移动一位
	 */
	@Override
	public int doStartTag() throws JspException {
		if(items.size()==0) {
			return SKIP_BODY;
		}else {
			Iterator<Object> it = items.iterator();
			pageContext.setAttribute(var, it.next());
			pageContext.setAttribute("it", it);
			return EVAL_BODY_INCLUDE;
		}
	} 
	
	@Override
	public int doAfterBody() throws JspException {
		Iterator<Object> it = (Iterator)pageContext.getAttribute("it");
		if(it.hasNext()) {
			pageContext.setAttribute(var, it.next());
			pageContext.setAttribute("it", it);
			return EVAL_BODY_AGAIN;
		}
		return EVAL_PAGE;
	}
	
}
           

数据标签

set 标签

public class SetTag extends BodyTagSupport {

	private static final long serialVersionUID = 4965191755704898746L;
	
	private String var;
	private Object value;
	
	@Override
	public int doStartTag() throws JspException {
		pageContext.setAttribute(var, value);
		return SKIP_BODY;
	}
	
	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;
	}
	
}
           

用checkbox标签试下:

先写个助手类把

public class CheckboxTag extends BodyTagSupport {
	
	
	private String textKey;//
	private String textVal;
	private List<Object> checkedVal=new ArrayList<>();//回显数据集合
	private List<Object> item=new ArrayList<>();//数据集合
	
	
	
	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 List<Object> getCheckedVal() {
		return checkedVal;
	}
	public void setCheckedVal(List<Object> checkedVal) {
		this.checkedVal = checkedVal;
	}
	public List<Object> getItem() {
		return item;
	}
	public void setItem(List<Object> item) {
		this.item = item;
	}
	public CheckboxTag(String textKey, String textVal, List<Object> checkedVal, List<Object> item) {
		super();
		this.textKey = textKey;
		this.textVal = textVal;
		this.checkedVal = checkedVal;
		this.item = item;
	}
	
	
	public CheckboxTag() {
		super();
	}
	
	@Override
	public int doStartTag() throws JspException {
		JspWriter out = pageContext.getOut();
		
			try {
				out.print(toHTML());
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		return super.doStartTag();
	}
	
	private String toHTML() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
		StringBuffer sb=new StringBuffer();
		String html;
		String value;
		for (Object obj : item) {
			Field fieldKey = obj.getClass().getDeclaredField(textKey);
			fieldKey.setAccessible(true);
			value = (String)fieldKey.get(obj);
			Field fieldVal = obj.getClass().getDeclaredField(textVal);
			fieldVal.setAccessible(true);
			html = (String)fieldVal.get(obj);	
			if(checkedVal.contains(value)) {
				sb.append("<input checked type='checkbox' value='"+value+"' />"+html+"");
			}
			else {
				sb.append("<input type='checkbox' value='"+value+"' />"+html+"");
			}
		}
		return sb.toString();
	}
	
	
}
           

然后就要在tld文件里写标签了

<tag>
  
  	<name>checkbox</name>//标签名称
  	<tag-class>com.zking.jsp.day02.CheckboxTag</tag-class>//助手类
  	<body-content>JSP</body-content>
  	<attribute>
  		<name>textKey</name>//属性
  		<required>true</required>//必须的,就为true,如果为false,快捷键就不会出来这个属性,需要自己打
  		<rtexprvalue>true</rtexprvalue>//是否支持表达式
  	</attribute>
  	<attribute>
  		<name>textVal</name>
  		<required>true</required>
  		<rtexprvalue>true</rtexprvalue>
  	</attribute>
  	<attribute>
  		<name>item</name>
  		<required>true</required>
  		<rtexprvalue>true</rtexprvalue>
  	</attribute>
  	<attribute>
  		<name>checkedVal</name>
  		<required>false</required>
  		<rtexprvalue>true</rtexprvalue>
  	</attribute>
  </tag>
           

然后验证标签是否正确

<%
		List list=new ArrayList();
		list.add(new Student("001","xiaoli"));
		list.add(new Student("002","laowang"));
		list.add(new Student("003","xiaocheng"));
		list.add(new Student("004","wangmazi"));
		List ls=new ArrayList();
		ls.add("002");
		ls.add("003");
		
		request.setAttribute("stus", list);
		request.setAttribute("ls", ls);
		

	<z:checkbox textVal="name" item="${stus}" checkedVal="${ls}" textKey="id"></z:checkbox>