欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jsp自定义标签

程序员文章站 2022-05-30 22:11:53
...

一. 标签语言特点

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

二.三大类标签

2.1 ui标签 c:out

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

2.2 控制标签 if /foreach/c

特点是控制的对象是标签体

2.3 数据标签 set

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

三:自定义标签的开发及使用步骤

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

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

rtexprvalue

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

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

3.3 在JSP通过taglib指令导入标签库,并通过指定后缀

访问自定义标签

四.了解标签的生命周期

jsp自定义标签

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

五:自定义set、out、if、foreach和select标签

jsp自定义标签
注:需要导入jar包

代码如下:

Teacher对象

<%@page import="com.lzy.jsp.Teacher"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
   <%@ taglib uri="/lengxi" prefix="z" %>
<!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>
 <z:set var="name" value="zs"></z:set>
<z:out value="${name }"></z:out>
<z:if test="false">状元</z:if>
<z:if test="true">刘光傻逼</z:if>
<%
List list=new ArrayList();
list.add(new Teacher("1","小"));
list.add(new Teacher("2","姐"));
list.add(new Teacher("3","姐"));
pageContext.setAttribute("teas", list);
%>
<z:foreach var="t" item="${teas}">
${t.tid }
${t.name }<br>
</z:foreach>
</body>
</html>

SetTag

package com.lzy.jsp;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
public class SetTag extends BodyTagSupport {
 /**
  * 数据标签库
  * 作用:
...........  * 是将value值赋给变量var
  */
 private static final long serialVersionUID = 8709372555354738223L;
    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.lzy.jsp;
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 {
 /**
  * out属性ui标签(需要展示效果,是依靠标签属性展示页面效果)
  * 
  */
 private static final long serialVersionUID = 350060231954560375L;
    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.lzy.jsp;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
public class IfTag extends BodyTagSupport {
 /**
  * if属于控制标签(页面展示效果依赖的是标签体)
  */
 private static final long serialVersionUID = 6260350038317584828L;
    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;
 }
}

ForeachTag

package com.lzy.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 = 6059068856674721600L;
 private String var;
 private List<Object> item=new ArrayList<Object>();
 public String getVar() {
  return var;
 }
 public void setVar(String var) {
  this.var = var;
 }
 public List<Object> getItem() {
  return item;
 }
 public void setItem(List<Object> item) {
  this.item = item;
 }
 /**
  * 执行完这个方法的时候  var所代表的指针一定要向下移动一位
  */
 @Override
 public int doStartTag() throws JspException {
  if(item.size()==0) {
   return SKIP_BODY;
  }else {
   Iterator<Object> it=item.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;
 } 
}

SelectTag

package com.lzy.jsp;
import java.io.IOException;
import java.lang.reflect.Field;
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  headerTextVal
 * 4、下拉框需要加载数据  item
 * 5、属性值接受数据库中保存的value值   selectedVal
 * 
 * 
*/
public class SelectTag extends BodyTagSupport{
private static final long serialVersionUID = 1L;
private String id;
 private String name;
 private List<Object> item=new ArrayList<Object>();
 private String textKey;
 private String textVal;
 private String selectedVal;
 private String headerTextKey;
 private String headerTextVal;
 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> getItem() {
  return item;
 }
 public void setItem(List<Object> item) {
  this.item = item;
 }
 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;
 }
@Override
 public int doStartTag() throws JspException {
  JspWriter out=pageContext.getOut();
  try {
   //  之所以能够在页面上看到select下拉框的效果  原因在于后台做了html的拼接
   out.print(toHTML());
  } catch (Exception e) {
   e.printStackTrace();
  }
  return super.doStartTag();
 }
private String toHTML() throws Exception, Exception {
  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 : item) {
//        底层代码
   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();
	}
}

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>lengxi 1.1 core library</description>
  <display-name>lengxi core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>c</short-name>
  <uri>/lengxi</uri>
  <tag>
  <!-- 填写的是标签库中的标签名 -->
    <name>demo1</name>
      <!-- 标签对应后台助手类 -->
    <tag-class>com.lzy.jsp.Demo1</tag-class>
      <!-- 标签库类名 -->
    <body-content>JSP</body-content>
    <attribute>
      <!-- 自定义标签中的属性 -->
        <name>test</name>
         <!-- 属性值是否必填 -->
        <required>true</required>
         <!-- 是否支持表达式-->
        <rtexprvalue>false</rtexprvalue>
    </attribute>
  </tag>
   <tag>
    <name>set</name>
    <tag-class>com.lzy.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>
  <tag>
    <name>out</name>
    <tag-class>com.lzy.jsp.OutTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>value</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
  <tag>
    <name>foreach</name>
    <tag-class>com.lzy.jsp.ForeachTag</tag-class>
    <body-content>JSP</body-content>
     <attribute>
        <name>var</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
    <attribute>
        <name>item</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
  <tag>
    <name>if</name>
    <tag-class>com.lzy.jsp.IfTag</tag-class>
    <body-content>JSP</body-content>
     <attribute>
        <name>test</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
   <tag>
    <name>select</name>
    <tag-class> com.lzy.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>item</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>selectedVal</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
        <name>headerTextKey</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
    <attribute>
        <name>headerTextVal</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
  </tag>
</taglib>

demo2测试

<%@page import="com.lzy.jsp.Teacher"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri="/lengxi" prefix="z" %>
<!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>
<h2>自定义set/out标签</h2> 
<z:set var="name" value="傻逼刘光"></z:set>
<z:out value="${name }"></z:out>
<h2>自定义if标签</h2> 
<z:if test="true">傻逼</z:if>
<z:if test="false">流光傻逼</z:if>
 <h2>自定义foreach标签</h2> 
<%
   List list=new ArrayList();
   list.add(new Teacher("1","傻"));
   list.add(new Teacher("2","逼"));
   list.add(new Teacher("3","刘"));
   list.add(new Teacher("4","光"));
   request.setAttribute("ter", list);
%>
 <z:foreach var="t" item="${ter }">
    ${t.tid },${t.name }<br>
 </z:foreach>
<h2>新增查询页面下拉框</h2>
<z:select textVal="name" item="${ter }" textKey="tid"></z:select>
<z:select textVal="name" headerTextKey="-1" headerTextVal="---请选择---" item="${ter }" textKey="tid"></z:select>
<h2>修改页面下拉框</h2>
<z:select headerTextKey="-1" headerTextVal="--请选择--" textVal="name" item="${ter }" textKey="tid" selectedVal="2"></z:select>
</body>
</html>


代码效果
jsp自定义标签