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

jsp自定义标签

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

1. 标签语言特点

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

空标签


   <br/><hr/>

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

ui标签
控制标签
数据标签

2. 自定义标签的开发及使用步骤

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

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

3. 标签生命周期

                                SKIP_BODY

3.1 实例化标签助手类->doStartTag()------------->doEndTag()
//主要用开发简单标签

                                  EVAL_BODY_INCLUDE        SKIP_BODY

3.2 实例化标签助手类->doStartTag()------------->doAfterBody---------------->doEndTag()…
EVAL_BODY_AGAIN

3.3 …

jsp自定义标签

SKIP_BODY:跳过主体
EVAL_BODY_INCLUDE:计算标签主体内容并[输出]
EVAL_BODY_BUFFERED:计算标签主体内容并[缓存]
EVAL_PAGE:计算页面的后续部分
SKIP_PAGE:跳过页面的后续部分
EVAL_BODY_AGAIN:再计算主体一次
备注:1、标签库的运作离不开tld文件 。 2、标签库的标签是定义在tld中的tag标签内(助手类)

4.实践

set助手

package com.likang.jsp;

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

public class SetTag extends BodyTagSupport{

	private static final long serialVersionUID = -6620809487950787524L;

	private String var;
	private String value;
	public String getVar() {
		return var;
	}
	public void setVar(String var) {
		this.var = var;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	
	@Override
	public int doStartTag() throws JspException {
		// TODO Auto-generated method stub
		pageContext.setAttribute(var, value);
		return SKIP_BODY;
	}
}

out助手

package com.likang.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 = 7607395783929157755L;

	
	private String value;


	public String getValue() {
		return value;
	}


	public void setValue(String value) {
		this.value = value;
	}
	
	@Override
	public int doStartTag() throws JspException {
		// TODO Auto-generated method stub
		JspWriter out = pageContext.getOut();
		try {
			out.print(value);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SKIP_BODY;
	}
}

if助手

package com.likang.jsp;

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

public class IfTag extends BodyTagSupport{

	private static final long serialVersionUID = 1L;

	private boolean test;

	public boolean isTest() {
		return test;
	}

	public void setTest(boolean test) {
		this.test = test;
	}
	
	@Override
	public int doStartTag() throws JspException {
		// TODO Auto-generated method stub
		return test ? EVAL_BODY_INCLUDE :SKIP_BODY;
	}
	
}

foreach助手

package com.likang.jsp;

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

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
/**
 * c:foreach
 * var 指针
 * items 指的是需要遍历的集合对象
 * <c:foreach var="stu" items="stus">
 * ${stu.name}...
 * <c/foreach}
 * @author Hasee
 *
 */
public class ForeachTag extends BodyTagSupport{

	private static final long serialVersionUID = 1L;

	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 {
		// TODO Auto-generated method stub
	//获取已经保存了的迭代器
		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;
	}
	
}

select助手

package com.likang.jsp;

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

import com.sun.org.apache.xml.internal.serializer.ToHTMLSAXHandler;
import com.sun.org.apache.xml.internal.serializer.ToHTMLStream;

/**
 * <select id='' name=''>
 * <option value='' selected></option>
 * </select>
 * 查询维度:下拉列表
 * 修改页面:下拉列表   数据回显
 * 
 * 
 * 1。id,name
 * 2,数据源,存入数据库中值textKey,展示列textVal
 * 3,加入属性(默认的头部属性值,默认的展示列值)
 * 4,加入属性,能够实现数据回显的功能selectdVal
 * @author Hasee
 *
 */
public class SelectTag extends BodyTagSupport{

	private static final long serialVersionUID = 1L;

	private String id;
	private String name;
	private List<Object> items=new ArrayList<Object>();
	
	private String textKey;
	private String textVal;
	private String headTextKey;
	private String headTextVal;
	private String selectedVal;
	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 getHeadTextKey() {
		return headTextKey;
	}
	public void setHeadTextKey(String headTextKey) {
		this.headTextKey = headTextKey;
	}
	public String getHeadTextVal() {
		return headTextVal;
	}
	public void setHeadTextVal(String headTextVal) {
		this.headTextVal = headTextVal;
	}
	public String getSelectedVal() {
		return selectedVal;
	}
	public void setSelectedVal(String selectedVal) {
		this.selectedVal = selectedVal;
	}
	
	@Override
	public int doStartTag() throws JspException {
		JspWriter out = pageContext.getOut();
		try {
			out.write(toTHML());
		} catch (Exception e) {
			// TODO: handle exception
		}
		return super.doStartTag();
	}
	/**
	 * 拼接出下拉列表对应的select的html代码
	 * @return
	 * @throws NoSuchMethodException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws SecurityException 
	 * @throws NoSuchFieldException 
	 */
	private String toTHML() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException, SecurityException {
		// TODO Auto-generated method stub
		StringBuffer sb=new StringBuffer();
		sb.append("<select id='"+id+"' name='"+name+"'>");
		
		if(!(headTextKey==null || "".equals(headTextKey)  ||  headTextVal==null ||  headTextVal.equals(""))) {
			sb.append("<option value='"+headTextKey+"' selected>"+headTextVal+" </option>   ");
		}
		String val;
		String html;
		for (Object obj : items) {
			//让学生id存入数据库,让学生的名字展示
			Field declaredField = obj.getClass().getDeclaredField(textKey);
			declaredField.setAccessible(true);
			val =(String) declaredField.get(obj);
			html=BeanUtils.getProperty(obj, textVal);
			
			if(val.equals(selectedVal)) {
				sb.append("<option value='"+val+"' selected>"+html+" </option>");
				
			}else {
				sb.append("<option value='"+val+"'  >"+html+"</option> ");
			}
		}
		
		sb.append("</select>");
		return sb.toString();
	}
	
	
}

学生实体类

package com.likang.jsp;

public class Student {
	private String sid;

	private String sname;

	public Integer age;

	public Student() {
		super();
		System.out.println("调用无参构造方法创建了一个学生对象");
	}

	public Student(String sid) {
		super();
		this.sid = sid;
		System.out.println("调用带一个参数的构造方法创建了一个学生对象");
	}

	public Student(String sid, String sname) {
		super();
		this.sid = sid;
		this.sname = sname;
		System.out.println("调用带二个参数的构造方法创建了一个学生对象");
	}

	@SuppressWarnings("unused")
	private Student(Integer age) {
		System.out.println("调用Student类私有的构造方法创建一个学生对象");
		this.age = age;
	}

	public String getSid() {
		return sid;
	}

	public void setSid(String sid) {
		this.sid = sid;
	}

	public String getSname() {
		return sname;
	}

	public void setSname(String sname) {
		this.sname = sname;
	}

	public void hello() {
		System.out.println("你好!我是" + this.sname);
	}

	public void hello(String name) {
		System.out.println(name + "你好!我是" + this.sname);
	}

	@SuppressWarnings("unused")
	private Integer add(Integer a, Integer b) {
		return new Integer(a.intValue() + b.intValue());
	}
}

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>zking 1.1 core library</description>
	<display-name>zking core</display-name>
	<tlib-version>1.1</tlib-version>
	<short-name>z</short-name>
	<uri>/lk</uri>
	
	<tag>
	<!-- 标签库中的标签(类似c:set  c:out的定义) -->
	<name>set</name>
	<!-- 是标签运行的具体代码,也就是助手类,下面填写的是助手类的全路径名 -->
	<tag-class>com.likang.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.likang.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.likang.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.likang.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>
	
	
	<tag>
	<name>select</name>
	<tag-class>com.likang.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>headTextKey</name>
	<required>false</required>
	<rtexprvalue>false</rtexprvalue>
	</attribute>
	<attribute>
	<name>headTextVal</name>
	<required>false</required>
	<rtexprvalue>false</rtexprvalue>
	</attribute>
	<attribute>
	<name>selectedVal</name>
	<required>false</required>
	<rtexprvalue>false</rtexprvalue>
	</attribute>
	
	</tag>
	
	
	
</taglib>

jsp页面

<%@page import="com.likang.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="/lk"  prefix="x"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<x:set var="name" value="无极剑圣"></x:set>
<x:out value="${name}"></x:out>

<x:if test="true">你好</x:if>
<x:if test="false">去世</x:if>

<%
List list=new ArrayList();
list.add(new Student("s001","无极剑圣"));
list.add(new Student("s004","无双剑姬"));
list.add(new Student("s003","暗裔剑魔"));
list.add(new Student("s002","疾风剑豪"));
request.setAttribute("stus", list);
%>
<br>
<x:foreach items="${stus }" var="stu">
${stu.sid },${stu.sname}<br>
</x:foreach>


<x:select textVal="sname" selectedVal="s004" headTextKey="-1" headTextVal="请选择" items="${stus }" textKey="sid"></x:select>

</body>
</html>

结果如下
jsp自定义标签