jsp自定义标签库

标签的概念:

标签
标签是一种XML元素,通过标签可以使JSP网页变得简洁并且易于维护,还可以方便地实现同一个JSP文件支持多种语言版本。由于标签是XML元素,所以它的名称和属性都是大小写敏感的

标签处理类
标签处理类似是Java类,这个类继承了TagSupport或者扩展了SimpleTag接口,通过这个类可以实现自定义JSP标签的具体功能

标签语言特点
<开始标签 属性=“属性值”>标签体</结束标签>
空标签
<开始标签></结束标签>
<开始标签/>

ui标签
控制标签 if /foreach
数据标签 set

自定义标签的开发及使用步骤
1 . 创建一个标签助手类(继承BodyTagSupport)
标签属性必须助手类的属性对应、且要提供对应get/set方法
rtexprvalue

2 . 创建标签库描述文件(tld),添加自定义标签的配置
注:tld文件必须保存到WEB-INF目录或其子目录

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

4 . 使用标签库的时候需要导入jar包
在这里插入图片描述

//	序列号的作用是方便对象序列化,序列化实际上就是将对象按照特定的规则持久化到硬盘
private static final long serialVersionUID = 2102051784152825544L;

代码:
SetTag:

package com.xhh.jsp.tag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
/**
 * 
 * 数据标签(不需要展示内容)
 * 作用:
 * 是将value值赋给var
 * @author linyaodong
 *
 */
public class SetTag extends BodyTagSupport {
	private static final long serialVersionUID = 7076852223410589098L;
    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);
    	return SKIP_BODY;
    }
}

OutTag:

package com.xhh.jsp.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
/**
 * out属性UI(标签效果,是依靠标签属性展现页面效果)
 * @author linyaodong
 *
 */
public class OutTag extends BodyTagSupport {

	private static final long serialVersionUID = -244786502784959729L;
	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 super.doStartTag();
	}
}

IfTag:

package com.xhh.jsp.tag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
/**
 * if属于控制标签(页面展示效果依赖的是标签体)
 * @author linyaodong
 *
 */
public class IfTag extends BodyTagSupport {
	private static final long serialVersionUID = 2102051784152825544L;
	private boolean test;
	public boolean isTest() {
		return test;
	}
	public void setTest(boolean test) {
		this.test = test;
	}
	@Override
	public int doStartTag() throws JspException {
		return test ? EVAL_BODY_INCLUDE : SKIP_BODY;
	}
}

z.tld:

<?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>xhh 1.1 core library</description>
	<display-name>xhh core</display-name>
	<tlib-version>1.1</tlib-version>
	<short-name>c</short-name>
	<uri>/xhh</uri>
	
	<!-- set --> 
  <tag>
    <!-- 标签库中的标签  (类似c:set c:out的定义) -->
    <name>set</name>
    <!-- 是标签运行具体代码,也就是助手类,下面填写的助手类的全路径名 -->
    <tag-class>com.xhh.jsp.tag.SetTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <!-- 该标签的属性 -->
        <name>var</name>
        <!-- 该属性是否必填 -->
        <required>true</required>
        <!-- 是否支持表达式 -->
        <rtexprvalue>false</rtexprvalue>
    </attribute>
     <attribute>
        <!-- 该标签的属性 -->
        <name>value</name>
        <!-- 该属性是否必填 -->
        <required>true</required>
        <!-- 是否支持表达式 -->
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>

<!-- out -->   
  	<tag>
    <name>out</name>
    <tag-class>com.xhh.jsp.tag.OutTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>value</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
 
 <!-- if -->  
  	<tag>
    <name>if</name>
    <tag-class>com.xhh.jsp.tag.IfTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>test</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
</taglib>

jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib  prefix="z" uri="/xhh"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>2</title>
</head>
<body>
<z:set var="name" value="xhh"></z:set>
<z:out value="${name}"></z:out>
<z:if test="true">linyaodong</z:if>
<z:if test="false">sb</z:if>
</body>
</html>

运行结果:
在这里插入图片描述
ForEachTag:

package com.xhh.jsp.tag;

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

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

public class ForeachTag extends BodyTagSupport {
	private static final long serialVersionUID = 1L;
	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;
	}
    @Override
    public int doStartTag() throws JspException {
    	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<Object>) pageContext.getAttribute("it");
    	if(it.hasNext()) {
    		pageContext.setAttribute(var, it.next());
    		pageContext.setAttribute("it", it);
    		return EVAL_BODY_AGAIN;
    	}
    	return EVAL_PAGE;
    }
}

z.tld

  <tag>
    <name>foreach</name>
    <tag-class>com.xhh.jsp.tag.ForeachTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>var</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
    <attribute>
        <name>items</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>

jsp页面:

<%@page import="com.xhh.entity.Student"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib  prefix="z" uri="/xhh"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>2</title>
</head>
<body>
<z:set var="name" value="xhh"></z:set>
<z:out value="${name}"></z:out>
<z:if test="true">linyaodong</z:if>
<z:if test="false">sb</z:if>
<br>
<%
      List <Student> list = new ArrayList<Student>();
      list.add(new Student("1","林"));
      list.add(new Student("2","耀"));
      list.add(new Student("3","东"));
      request.setAttribute("data", list);
   %>
  <z:foreach items="${data}" var="t">
        ${t.tid}
        ${t.tname}<br>
  </z:foreach>

</body>
</html>

运行结果:
在这里插入图片描述
SelectTag:
第三方工具包需要导入jar架包

package com.xhh.jsp.tag;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

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

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;


import org.apache.commons.beanutils.PropertyUtils;
/**
 * 自定义select标签应具备的功能
 * 1.新增查询页面,只要通过一个标签就可以完成数据的绑定,而并非使用c:foreach绑定
 * 2.修改页面,同样通过一个自定义标签完成数据的遍历的展示,以及默认选中指定项
 * 
 * 思考:
 *   1.要往后台传值 id,name
 *   2.定义数据库存储的对应的标签属性,前台页面展示的标签属性  textKey,textVal
 *   3.定义下拉框的默认值headerTextKey,headTextVal
 *   4.下拉框需要加载数据  items
 *   5.属性值接受数据库中保存的value值   selectedVal
 *   
 *  属于UI标签
 * @author linyaodong
 *
 */
public class SelectTag extends BodyTagSupport{
	private static final long serialVersionUID = 6885147458102952045L;
	private String id;
	private String name;
	private List<Object> items = new ArrayList<>();
	private String textkey;
	private String textval;
	private String headkey;
	private String headval;
	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 getHeadkey() {
		return headkey;
	}
	public void setHeadkey(String headkey) {
		this.headkey = headkey;
	}
	public String getHeadval() {
		return headval;
	}
	public void setHeadval(String headval) {
		this.headval = headval;
	}
	public String getSelectedval() {
		return selectedval;
	}
	public void setSelectedval(String selectedval) {
		this.selectedval = selectedval;
	}
	
	
	
	
	@Override
	public int doStartTag() throws JspException {
		JspWriter out = pageContext.getOut();
		
		try {
			//对你想展现在页面上的html代码进行拼接
			out.print(toHTML());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return super.doStartTag();
	}
	
	//拼接标签代码
	private String toHTML() throws Exception, Exception {
		StringBuilder sb = new StringBuilder();//更快
		sb.append("<select id='"+id+"' name='"+name+"'>");
		//加载类似于下拉框默认显示的 请选择 
		//判定是否有值 
		if(!(headkey == null || "".equals(headkey) || headval == null || "".equals(headval))) {
			sb.append("<option selected value='"+headkey+"'>"+headval+"</option>");
		}
		
		
		String val = "";//写option value 的
		String html = "";//写在option标签体的 展示看
		
		//循环打印数据 items = value 
		for (Object obj : items) {
			Field f = obj.getClass().getDeclaredField(textkey);
			f.setAccessible(true);
			val = (String) f.get(obj);
			f = obj.getClass().getDeclaredField(textval);
			f.setAccessible(true);
			html = (String) f.get(obj);
			//考虑如果是修改页面时,下拉框回选数据库所存储的值 也就是默认选中数据库所存储的值
			if(val.equals(selectedval)) {
				sb.append("<option selected value='"+val+"'>"+html+"</option>");
			}else {
				sb.append("<option value='"+val+"'>"+html+"</option>");
			}
		}
		
		sb.append("</select>");
		return sb.toString();//返回拼接的值
	}
}

z.tld:

<!-- select标签 -->
  <tag>
    <name>select</name>
    <tag-class>com.xhh.jsp.tag.SelectTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>id</name> 
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
    <attribute>
        <name>name</name>
        <required>false</required>
        <rtexprvalue>false</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>false</rtexprvalue>
    </attribute>
    <attribute>
        <name>headkey</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute><attribute>
        <name>headval</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
    <attribute>
        <name>selectedval</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>

jsp页面

<!-- select -->
<h2>新增查询页面下拉框</h2>
<z:select textval="tname" items="${data}" textkey="tid"></z:select>
<hr>
<z:select headkey="-1" headval="--请选择--" textval="tname" items="${data }" textkey="tid"></z:select>
<hr>
<h2>修改页面下拉框</h2>
<z:select headkey="-1" headval="--请选择--" textval="tname" items="${data}" textkey="tid" selectedval="2"></z:select>

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值