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

jsp自定义标签

程序员文章站 2022-05-30 20:50:59
...

一. 标签语言特点

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

二.三大类标签

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包

代码如下:

Student对象

package com.xwt.jsp;
/**
 * 实体类
 * @author 婉婷宝贝
 *
 */
public class Student {
	private String id;
	private String name;
	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 Student() {}
	
	public Student(String id, String name) {
		super();
		this.id = id;
		this.name = name;
	}	
}

SetTag

package com.xwt.jsp;

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

public class SetTag extends BodyTagSupport{

	private static final long serialVersionUID = -3088388271118796905L;

	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.xwt.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{

	private static final long serialVersionUID = 857127606631889677L;
	
	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.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SKIP_BODY;
	}
}

IFTag

package com.xwt.jsp;

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

public class IFTag extends BodyTagSupport{

	private static final long serialVersionUID = -2974635242176594802L;

	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.xwt.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 = 1673290044200807388L;

	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.xwt.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
 * 
 * @author 婉婷宝贝
 *
 */
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>zting 1.1 core library</description>
  <display-name>zting core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>c</short-name>
  <uri>/zting</uri>

  <tag>
  <!-- 填写的是标签中的标签名 -->
    <name>demo</name>
    <!-- 标签对应后台助手类 -->
    <tag-class>com.xwt.jsp.tag.DemoTag</tag-class>
    <!-- 标签类别 -->
    <body-content>JSP</body-content>
    <attribute>
    <!-- 自定义标签中属性 -->
        <name>test</name>
        <!-- 属性值是否必填 -->
        <required>true</required>
        <!-- 是否支持表达式(EL/ognl)表达式 -->
        <rtexprvalue>false</rtexprvalue>
    </attribute>
  </tag>
  
   <tag>
    <name>set</name>
    <tag-class>com.xwt.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.xwt.jsp.OutTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>value</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
  
    <tag>
    <name>if</name>
    <tag-class>com.xwt.jsp.IFTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>test</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
  
  <tag>
    <name>foreach</name>
    <tag-class>com.xwt.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>select</name>
    <tag-class> com.xwt.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.xwt.jsp.Student"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib uri="/zting" prefix="t" %>
<!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> 
<t:set var="name" value="星星"></t:set>
<t:out value="${name }"></t:out>

<h2>自定义if标签</h2> 
<t:if test="true">感情</t:if>
<t:if test="false">和你</t:if>
  
 <h2>自定义foreach标签</h2> 
<%
   List list=new ArrayList();
   list.add(new Student("t001","李翔"));
   list.add(new Student("t002","李状元"));
   list.add(new Student("t003","陈阳"));
   list.add(new Student("t004","刘光"));
   request.setAttribute("stus", list);
%>
 <t:foreach var="stu" item="${stus }">
    ${stu.id },${stu.name }<br>
 </t:foreach>

<h2>新增查询页面下拉框</h2>
<t:select textVal="name" item="${stus }" textKey="id"></t:select>
<t:select textVal="name" headerTextKey="-1" headerTextVal="---请选择---" item="${stus }" textKey="id"></t:select>

<h2>修改页面下拉框</h2>
<t:select headerTextKey="-1" headerTextVal="--请选择--" textVal="name" item="${stus }" textKey="id" selectedVal="2"></t:select>
 
</body>
</html>

set、out、if、foreach运行图如下:

jsp自定义标签
foreach、select标签运行图:
jsp自定义标签

相关标签: jsp自定义标签