jsp自定义标签(set/out/if/foreach/select)

1.定义标签开发步骤

使用标签库的时候需要导入jar包

链接:https://pan.baidu.com/s/1ZQNjIn6ANt8v25Y8NYpP0g
提取码:6ky4

1.1助手类

创建一个标签助手类(继承BodyTagSupport)
标签属性必须助手类的属性对应,且要提供对应get/set方法
rtexprvalue

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

代码演示:

SetTag:

package com.myy.jsp;

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

/**
 * 数据标签(不需要展示内容)
 * 作用:
 *  是将value值赋给var
 * @author myy
 *
 */
public class SetTag extends BodyTagSupport{

	private static final long serialVersionUID = 3133721423340785419L;

	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.myy.jsp;

import java.io.IOException;

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

/**
 * out属于UI标签(需要展示效果,是依靠标签属性展示页面效果)
 * JspWriter
 * @author myy
 *
 */
public class OutTag extends BodyTagSupport{

	private static final long serialVersionUID = -3045137795406213666L;
	
	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) {
			e.printStackTrace();
		}
		return super.doStartTag();
	}
	
}

IfTag:

package com.myy.jsp;

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

/**
 * if属于控制标签(页面展示效果依赖的是标签体)
 * @author myy
 *
 */
public class IfTag extends BodyTagSupport{

	private static final long serialVersionUID = 2558745568811999599L;
	
	private Boolean test;

	public Boolean getTest() {
		return test;
	}

	public void setTest(Boolean test) {
		this.test = test;
	}
	
	public int doStartTag() throws JspException {
		return test ? EVAL_BODY_INCLUDE : SKIP_BODY;
	}
	
}

ForeachTag:

package com.myy.jsp;

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 = -2364828486746117631L;

	private List<Object> items = new ArrayList<>();
	
	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;
	}
	
	public int doStartTag() throws JspException {
		Iterator<Object> it = items.iterator();
		pageContext.setAttribute(var, it.next());
		pageContext.setAttribute("it",it);
		
		return EVAL_BODY_INCLUDE;
		
	}
	
	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;
		}else {
			return EVAL_PAGE;
		}
		
		
	}
	
}

SelectTag:

用第三方工具包方法需要导入jar包:
链接:https://pan.baidu.com/s/1jcWF-3MBcyoQMzCn2dtfDQ
提取码:o2n4

package com.myy.jsp;

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.PropertyUtils;

/**
 * 自定义select标签应具备的功能
 * 1.新增查询页面,只要通过一个标签就可以完成数据的绑定,而并非使用c:foreach绑定
 * 2.修改页面,同样通过一个自定义标签完成数据的遍历的展示,以及默认选中指定项
 * 
 * 思考:
 *   1.要往后台传值 id,name
 *   2.定义数据库存储的对应的标签属性,前台页面展示的标签属性  textKey,textVal
 *   3.定义下拉框的默认值headerTextKey,headTextVal
 *   4.下拉框需要加载数据  items
 *   5.属性值接受数据库中保存的value值   selectedVal
 *   
 *  属于UI标签
 * @author myy
 *
 */
public class SelectTag extends BodyTagSupport{

	private static final long serialVersionUID = -9207356299473130587L;

    private String id;
    private String name;
    private List<Object> items = new ArrayList<>();
    private String textKey;
    private String textVal;
    private String headerTextKey;
    private String headerTextVal;
    private String selectedVal;
    
    @Override
    public int doStartTag() throws JspException {
    	JspWriter out = pageContext.getOut();
    	try {
//    		之所以能够在页面上看到select下拉框的效果,原因在于后台做了html代码的拼接
			out.print(toHTML());
		} catch (IOException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			e.printStackTrace();
		}
    	return super.doStartTag();
    }
    
	private String toHTML() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		StringBuilder sb = new StringBuilder();
		String value = "";
		String html = ""; 
		sb.append("<select id='"+id+"' name='"+name+"'>");
        if(!(headerTextKey == null || "".equals(headerTextKey) || headerTextVal == null || "".equals(headerTextVal))) {
        	sb.append("<option selected value='"+headerTextKey+"'>"+headerTextVal+"</option>");	
        }
//		items=data,textKey=sid,textVal=sname
		for (Object obj : items) {
//        底层代码
			Field f = obj.getClass().getDeclaredField(textKey);
			f.setAccessible(true);
			value = (String) f.get(obj);
//		第三方工具包方法
			html = (String) PropertyUtils.getProperty(obj, textVal);
			
//			考虑如果是修改页面需要下拉框回选数据库存储的值
			if(value.equals(selectedVal)) {
				sb.append("<option selected value='"+value+"'>"+html+"</option>");
			}
			else {
				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 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 String getSelectedVal() {
		return selectedVal;
	}
	public void setSelectedVal(String selectedVal) {
		this.selectedVal = selectedVal;
	}
    
	
}

1.2 tld

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

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

代码演示:

在你的web应用目录下,找到WEB-INF文件夹,在里面新建一个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>myy 1.1 core library</description>
  <display-name>myy core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>c</short-name>
  <uri>/myy</uri>

  <tag>
  <!-- 填写的是标签库中的标签 -->
    <name>demo</name>
    <!-- 标签对应的后台助手类(每在页面上写标签都会去访问后台代码) -->
    <tag-class>com.myy.jsp.DemoTag</tag-class>
   <!-- 标签类别 -->
    <body-content>JSP</body-content>
    <attribute>
    <!-- 自定义标签中的属性 -->
        <name>test</name>
        <!-- 属性值是否必填 -->
        <required>true</required>
        <!-- 是否支持表达式EL表达式/ognl表达式 -->
        <rtexprvalue>false</rtexprvalue>
    </attribute>
  </tag>
  
   <!-- set标签 -->
  <tag>
    <name>set</name>
    <tag-class>com.myy.jsp.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.myy.jsp.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.myy.jsp.IfTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>test</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
  
 
 <!-- foreach标签 -->
  <tag>
    <name>foreach</name>
    <tag-class>com.myy.jsp.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>
  
   <!-- select标签 -->
  <tag>
    <name>select</name>
    <tag-class>com.myy.jsp.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>headerTextKey</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
    <attribute>
        <name>headerTextVal</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
    <attribute>
        <name>selectedVal</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
  
</taglib>

demo2测试

<%@page import="com.myy.jsp.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="m" uri="/myy" %>
<!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>jsp自定义标签</title>
</head>
<body>
<!-- set,out -->
<m:set var="name" value="myy"></m:set>
<m:out value="${name}"></m:out>
<hr>
<!-- if -->
<m:if test="true">zs</m:if>
<m:if test="false">ls</m:if>
<hr>

<!-- foreach -->
<%
/* 模拟查过来的集合 */
  List list = new ArrayList();
  list.add(new Student("1","小明"));
  list.add(new Student("2","小红"));
  list.add(new Student("3","小白"));
  pageContext.setAttribute("data", list);
%>
 <m:foreach items="${data}" var="t">
  ${t.sid},${t.sname}<br>
</m:foreach> 
<hr>

<!-- select -->
  <h2>新增查询页面下拉框</h2>
  <m:select textVal="sname" items="${data }" textKey="sid"></m:select>
<hr>
<m:select headerTextKey="-1" headerTextVal="--请选择--" textVal="sname" items="${data }" textKey="sid"></m:select>
<hr>
 <h2>修改页面下拉框</h2>
 <m:select headerTextKey="-1" headerTextVal="--请选择--" textVal="sname" items="${data }" textKey="sid" selectedVal="2"></m:select>
 
</body>
</html>

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

1.3 taglib

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

2.UI标签

c:out
特点是显示数据,并且数据不是来源于标签体的,而是来源于jsp标签本身

3.控制标签

c:if
c:foreach
特点是控制的对象是标签体

4.数据标签

c:set
特点是存储数据,没有任何的页面效果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值