J2EE基础-自定义JSP标签(foreach和select)

目录

一、自定义Foreach标签

A、分析

B、助手类

C、.tld 文件

D、jsp 文件

执行结果

 二、自定义select标签

A、目标

B、分析

C、助手类

D、.tld文件

E、JSP界面

执行结果

 当做数据回显时,无需增加if判断,无需增加新的代码

 执行结果


一、自定义Foreach标签

A、分析

<c:forEach items="${clas2 }" var="c">

以上述代码为例,我们对此分析一下。

首先我们能够看出来有两个属性

items:list<Object>
var:String

两条路线:

EVAL_BODY_INCLUDE (计算标签主体内容并[输出])
EVAL_BODY_AGAIN  (再计算主体一次)

B、助手类

ForeachTag类:

package com.oyang.tag;

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

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

/**
 *<c:forEach items="${clas2 }" var="c">
 * @author yang 
 *
 * @date 2022年6月21日上午8:49:55
 */
public class ForeachTag extends BodyTagSupport{
	private String var;
	private List<Object> items;
	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();
//<option value="${c.cid }">${c.cname}</option>
//var =c,it.next()是集合汇总的某一个对象  /  pageContext.setAttribute("c", items.get(0)某一个元素);
		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;
		}else {
			return EVAL_PAGE;
		}
	}	 
}

C、.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>JSTL 1.1 core library</description>
  <display-name>JSTL core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>y</short-name>
  <uri>https://blog.csdn.net/weixin_65211978?type=blog</uri>

  <validator>
    <description>
        Provides core validation features for JSTL tags.
    </description>
    <validator-class>
        org.apache.taglibs.standard.tlv.JstlCoreTLV
    </validator-class>
  </validator>

  <tag>
 <!--  代表标签库 标签的名字 -->
    <name>demo1</name>
    <!-- 该标签对应的助手类 -->
    <tag-class>com.oyang.tag.DemoTag1</tag-class>
    <!-- 代表是一个JSP标签 -->
    <body-content>JSP</body-content>
<!--     <attribute> -->
    <!-- 该自定义JSP标签 属性的名称 -->
<!--         <name>var</name> -->
        <!-- 该属性是否必填 -->
      <!--   <required>false</required> -->
        <!-- 该属性是否支持表达式 -->
       <!--  <rtexprvalue>false</rtexprvalue> -->
<!--     </attribute> -->
  </tag>
   <tag>
    <name>for</name>
    <tag-class>com.oyang.tag.ForeachTag</tag-class>
    <body-content>JSP</body-content>
     <attribute> 
        <name>items</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute> 
        <name>var</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
  </tag>
</taglib>

D、jsp 文件

<%@page import="java.util.ArrayList"%>
<%@page import="com.oyang.entity.Teacher"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="https://blog.csdn.net/weixin_65211978?type=blog" prefix="y"%>
<!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>Insert title here</title>
</head>
<body>
<y:demo1>xx</y:demo1>
<%
	List<Teacher> ls=new ArrayList<>();
	ls.add(new Teacher("t001","yang"));
	ls.add(new Teacher("t002","oyang"));
	ls.add(new Teacher("t003","liujiujie"));
	ls.add(new Teacher("t004","xielaoba"));
	ls.add(new Teacher("t005","liaoji"));
	request.setAttribute("list", ls);
%>
<y:for items="${list}" var="y">
	${y.tid} : ${y.name}
</y:for>
</body>
</html> 

执行结果

 二、自定义select标签

A、目标

1.省略遍历的过程,做到只需要一行就能实现select标签

2.当做数据回显时,无需增加if判断,无需增加新的代码

B、分析

分析:
后台要遍历->数据源->items
需要一个对象的属性代表下拉框对应的展示内容->textVal
需要一个对象的属性代表下拉框对应的value值->textkey
默认的头部选项展示内容->haederTextVal

默认的头部选项值->haederTextKey
数据中存储的值,为了方便做数据回显->selectdVal
id(设置样式)
name(设置样式)

C、助手类

SelectTag类:

package com.oyang.tag;

import java.io.IOException;
import java.lang.reflect.Field;
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;

/**
 * @author yang 
 * @date 2022年6月21日上午9:49:59
 */
public class SelectTag	extends BodyTagSupport{
	private List<Object> items;
	private String textVal;//teacher的name
	private String textKey;
	private String haederTextVal;
	private String haederTextKey;
	private String selectdVal;
	private String id;
	private String name;
	
	@Override
	public int doStartTag() throws JspException {
		JspWriter out = pageContext.getOut();
		try {
			out.print(toHTML());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return super.doStartTag();
	}
	
	private String toHTML() throws Exception, Exception {
		StringBuffer sb=new StringBuffer();
		sb.append("<select id='"+id+"' name='"+name+"'>");
		if(haederTextVal!=null&&!"".equals(haederTextVal)) {
			sb.append("<option value='"+haederTextKey+"'>"+haederTextVal+"</option>");
		}
		for (Object obj : items) {
//			<y:select textVal="name" items="${list}" textKey="tid"></y:select>
			Field textKeyFiled = obj.getClass().getDeclaredField(textKey);
			textKeyFiled.setAccessible(true);
			Object value = textKeyFiled.get(obj);//真正下拉框展示值
			
			if(selectdVal!=null&&!"".equals(selectdVal)&&selectdVal.equals(value)) {
				sb.append("<option selected value='"+value+"'>"+PropertyUtils.getProperty(obj, textVal)+"</option>");
			}
			else {
				sb.append("<option value='"+value+"'>"+PropertyUtils.getProperty(obj, textVal)+"</option>");
			}
		}
		sb.append("</select>");
		return sb.toString();
	}

	public List<Object> getItems() {
		return items;
	}
	public void setItems(List<Object> items) {
		this.items = items;
	}
	public String getTextVal() {
		return textVal;
	}
	public void setTextVal(String textVal) {
		this.textVal = textVal;
	}
	public String getTextKey() {
		return textKey;
	}
	public void setTextKey(String textKey) {
		this.textKey = textKey;
	}
	public String getHaederTextVal() {
		return haederTextVal;
	}
	public void setHaederTextVal(String haederTextVal) {
		this.haederTextVal = haederTextVal;
	}
	public String getHaederTextKey() {
		return haederTextKey;
	}
	public void setHaederTextKey(String haederTextKey) {
		this.haederTextKey = haederTextKey;
	}
	public String getSelectdVal() {
		return selectdVal;
	}
	public void setSelectdVal(String selectdVal) {
		this.selectdVal = selectdVal;
	}
	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;
	}
	
}

D、.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>JSTL 1.1 core library</description>
  <display-name>JSTL core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>y</short-name>
  <uri>https://blog.csdn.net/weixin_65211978?type=blog</uri>

  <validator>
    <description>
        Provides core validation features for JSTL tags.
    </description>
    <validator-class>
        org.apache.taglibs.standard.tlv.JstlCoreTLV
    </validator-class>
  </validator>

  <tag>
 <!--  代表标签库 标签的名字 -->
    <name>demo1</name>
    <!-- 该标签对应的助手类 -->
    <tag-class>com.oyang.tag.DemoTag1</tag-class>
    <!-- 代表是一个JSP标签 -->
    <body-content>JSP</body-content>
<!--     <attribute> -->
    <!-- 该自定义JSP标签 属性的名称 -->
<!--         <name>var</name> -->
        <!-- 该属性是否必填 -->
      <!--   <required>false</required> -->
        <!-- 该属性是否支持表达式 -->
       <!--  <rtexprvalue>false</rtexprvalue> -->
<!--     </attribute> -->
  </tag>
    <tag>
    <name>select</name>
    <tag-class>com.oyang.tag.SelectTag</tag-class>
    <body-content>JSP</body-content>
     <attribute> 
        <name>items</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    
    <attribute> 
        <name>textVal</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
    
    <attribute> 
        <name>textKey</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
    
    <attribute> 
        <name>haederTextVal</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
    
    <attribute> 
        <name>haederTextKey</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
    
    <attribute> 
        <name>selectdVal</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    
    <attribute> 
        <name>id</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    
    <attribute> 
        <name>name</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
  </tag>
</taglib>

E、JSP界面

<%@page import="java.util.ArrayList"%>
<%@page import="com.oyang.entity.Teacher"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="https://blog.csdn.net/weixin_65211978?type=blog" prefix="y"%>
<!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>Insert title here</title>
<style type="text/css">
	#mysel{
		color: blue;
	}
</style>
</head>
<body>
<y:demo1>xx</y:demo1>
<%
	List<Teacher> ls=new ArrayList<>();
	ls.add(new Teacher("t001","yang"));
	ls.add(new Teacher("t002","oyang"));
	ls.add(new Teacher("t003","liujiujie"));
	ls.add(new Teacher("t004","xielaoba"));
	ls.add(new Teacher("t005","liaoji"));
	request.setAttribute("list", ls);
%>
<y:select selectdVal="t002" id="mysel" haederTextKey="-1" haederTextVal="==请选择==" textVal="name" items="${list}" textKey="tid"></y:select>
</body>
</html> 

执行结果

 当做数据回显时,无需增加if判断,无需增加新的代码

 

 

 上诉代码有,在此标记

 执行结果:

 默认选中了


 OK,今日的学习就到此结束啦,如果对个位看官有帮助的话可以留下免费的赞哦(收藏或关注也行),如果文章中有什么问题或不足以及需要改正的地方可以私信博主,博主会做出改正的。个位看官,小陽在此跟大家说拜拜啦! 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

歐陽。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值