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

JSP自定义标签

程序员文章站 2022-03-11 11:06:13
...

JSP自定义标签

一、基础标签介绍
1. 标签语言特点
<开始标签 属性=“属性值”>标签体</结束标签>

   空标签
   <br/><hr/>

<开始标签></结束标签>
<开始标签/>

ui标签 c:out
特点是显示数据,并且数据不是来源于标签体的,而是来源于jsp标签本身
控制标签 if /foreach
特点是控制的对象是标签体
数据标签 set
特点是存储数据,没有任何的页面效果

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

package com.wangjing.jsp.Tag;

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

public class DemoTag extends BodyTagSupport {

	/**
	 * ***的作用是方便对象进行序列化,序列化实际上就是将对象按照特定的规则持久化到硬盘
	 * 反序列化:把硬盘的对象读到内存当中
	 */
	private static final long serialVersionUID = -645661699234557954L;
private String test;
	
	
	public String getTest() {
		return test;
	}

	public void setTest(String test) {
		this.test = test;
	}

	@Override
		public int doStartTag() throws JspException {
			System.out.println(test);
			System.out.println("doStartTag-----------------------");
			return EVAL_BODY_INCLUDE;
		}
	
	@Override
		public int doEndTag() throws JspException {
			System.out.println("doEndTag-------------------------");
			return super.doEndTag();
		}
	
	@Override
		public int doAfterBody() throws JspException {
			System.out.println("doAfterBody----------------------");
			boolean flag = true;
			
			return flag ? EVAL_BODY_AGAIN : EVAL_PAGE;
		}
	
}

2.2 创建标签库描述文件(tld),添加自定义标签的配置
注:tld文件必须保存到WEB-INF目录或其子目录
2.3 在JSP通过taglib指令导入标签库,并通过指定后缀
访问自定义标签

3. 标签生命周期JSP自定义标签
SKIP_BODY:跳过主体
EVAL_BODY_INCLUDE:计算标签主体内容并[输出]
EVAL_PAGE:计算页面的后续部分
SKIP_PAGE:跳过页面的后续部分
EVAL_BODY_AGAIN:再计算主体一次
二、自定义标签
1. 自定义标签开发步骤
1.1 助手类
1.2 tld
1.3 taglib
2. UI标签
z:out 1
m:select 5

 <h1 value="xxx"></h1>

注1:JspWriter writer = pageContext.getOut();
3. 控制标签
m:if 2
m:forEach 3

<h1 >xxxx </h1>

注1:page(pageContext)|request(…)|session(…)|application(…)
存储和交换数据
B compare
4. 数据标签
m:set 4
数据标签就是用来存储数据的
c:set

  <h1></h1>

ehcache
仿写c标签:
out标签:

package com.wangjing.jsp.Tag;

import java.io.IOException;

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

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

	private static final long serialVersionUID = -4776951280538816832L;
	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();
	}
}

set标签:

package com.wangjing.jsp.Tag;

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

/**
 * 数据标签(不需要展示内容)
 * 作用:
 * 	是将value赋给变量var
 * @author wj
 *
 */
public class SetTag extends BodyTagSupport {
	private static final long serialVersionUID = -2130898555302253651L;
	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;
	}
}

if标签:

package com.wangjing.jsp.Tag;

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

/**
 * if属于控制标签(页面展示效果依赖于标签体)
 * @author wj
 *
 */
public class IfTag extends BodyTagSupport {
	private static final long serialVersionUID = -8075622033288162446L;
	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;
	}
}

foreach标签:

package com.wangjing.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 = -6048931116591412523L;
	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;
		}else{
			return EVAL_PAGE;
		}
		
	}
}

wangjing.tid:

<?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>wj 1.1 core library</description>
  <display-name>wj core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>c</short-name>
  <uri>/wangjing</uri>

   <tag>
    <name>set</name>
    <tag-class>com.wangjing.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>
  
   <tag>
    <name>out</name>
    <tag-class>com.wangjing.jsp.Tag.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.wangjing.jsp.Tag.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.wangjing.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>
</taglib>

显示代码:

<%@page import="com.wangjing.jsp.emtity.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="/wangjing" prefix="w" %>
<!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>
	
  <!--  ui标签	c:out -->
  
   <!-- 数据标签	set -->
	<c:set value="zs" var="name"></c:set>
	 <!--  ui标签	c:out -->
	<c:out value="${name}"></c:out>
	 <!-- 控制标签 if /foreach/c  -->
	<c:if test="true">ls</c:if>
	<c:if test="false">ww</c:if>
	<%
  		List list=new ArrayList();
  	list.add(new Teacher("1","胡"));
  	list.add(new Teacher("2","宇"));
  	list.add(new Teacher("3","飞"));
  	pageContext.setAttribute("teas", list);
  	%>
  	<w:foreach items="${teas}" var="t">
  		${t.tid},${t.tname}<br>
  	</w:foreach>
</body>
</html>

显示结果:
JSP自定义标签

自定义select标签:

package com.wangjing.jsp.Tag;

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

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

import org.apache.commons.beanutils.PropertyUtils;

/**
 * 自定义select标签应该具备的功能
 * 	1、新增查询页面,只能通过一个标签就可以完成数据的绑定,而并非使用c:foreach去循环绑定数据
 * 	2、修改页面同样通过一个自定义标签完成数据的遍历展示,以及默认选中指定
 * 	
 * 
 * 	思考(需要定义哪些属性):
 * 		1、要往后台传值  id,name
 * 		2、定义数据库存的对应的属性、前台页面展示的标签属性 textKey,textVal
 * 		3、定义下拉框的默认值  headerTextKey,headerTextVal
 * 		4、下拉框需要加载数据  itmes
 * 		5、属性值接收数据库中保存的value值   selectVal
 * @author wj
 *
 */

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

wangjing.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>wj 1.1 core library</description>
  <display-name>wj core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>c</short-name>
  <uri>/wangjing</uri>

	 <tag>
    <name>select</name>
    <tag-class>com.wangjing.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>headerTextKey</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
     <attribute>
        <name>headerTextVal</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
     <attribute>
        <name>selectVal</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
</taglib>

显示页码:

<%@page import="com.wangjing.jsp.emtity.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="/wangjing" prefix="w" %>
<!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>
<%--  <w:set var="name" value="zs"></w:set>
	<w:out value="${name}"></w:out>
  	<w:if test="true">ls</w:if>
  	<w:if test="false">ww</w:if>  --%>
  	
  	<%
  		List list=new ArrayList();
  	list.add(new Teacher("1","胡"));
  	list.add(new Teacher("2","宇"));
  	list.add(new Teacher("3","飞"));
  	pageContext.setAttribute("teas", list);
  	%>
  	<w:foreach items="${teas}" var="t">
  		${t.tid},${t.tname}<br>
  	</w:foreach>
  	<h2>新增查询页面下拉框</h2>
  	<w:select textVal="tname" items="${teas}" textKey="tid"></w:select>
  	<w:select textVal="tname" items="${teas}" textKey="tid" headerTextKey="-1" headerTextVal="---请选择---"></w:select>
  	<h2>修改页面下拉框</h2>
  	<w:select textVal="tname" items="${teas}" textKey="tid" headerTextKey="-1" headerTextVal="---请选择---" selectVal="3"></w:select>
</body>
</html>

显示结果:

JSP自定义标签

相关标签: 自定义jsp