JSP自定义标签

it2022-05-05  117

1. 标签语言特点

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

2.三大类标签

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

3.了解标签的生命周期图

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

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

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

2 创建标签库描述文件(tld),添加自定义标签的配置 注:tld文件必须保存到WEB-INF目录或其子目录

3 在JSP通过taglib指令导入标签库,并通过指定后缀 访问自定义标签

5.自定义set、out、if、foreach和select标签

测试用的Test1

package com.wangcong; public class Test1 { 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 Test1() { super(); } public Test1(String id, String name) { super(); this.id = id; this.name = name; } @Override public String toString() { return "Demo [id=" + id + ", name=" + name + "]"; } }

SetTag

package wangcong.tag; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.BodyTagSupport; public class SetTag extends BodyTagSupport { private static final long serialVersionUID = 3022286660316203872L; 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 { //将得到的数据value赋给var pageContext.setAttribute(var, value); return SKIP_BODY; } }

OutTag

package wangcong.tag; 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 = 3825465757059185456L; private Object value;//任意值 public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } @Override public int doStartTag() throws JspException { //将value写到页面去 JspWriter out = pageContext.getOut(); try { out.print(value); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return super.doStartTag(); } }

IfTag

package wangcong.tag; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.BodyTagSupport; public class IfTag extends BodyTagSupport{ private static final long serialVersionUID = -27885651335235798L; private boolean flag; public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } @Override public int doStartTag() throws JspException { return flag ? EVAL_BODY_INCLUDE : SKIP_BODY; } }

ForerchTag

package wangcong.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 = 4208690989932419067L; private String var;//名字 private List<Object> value = new ArrayList<>();//传过来的数据组 public String getVar() { return var; } public void setVar(String var) { this.var = var; } public List<Object> getValue() { return value; } public void setValue(List<Object> value) { this.value = value; } @Override public int doStartTag() throws JspException { //迭代器遍历传过来的数组 Iterator it = value.iterator(); pageContext.setAttribute(var, it.next()); pageContext.setAttribute("it", it); return EVAL_BODY_INCLUDE; } @Override public int doAfterBody() throws JspException { //获取原来的it Iterator it = (Iterator) pageContext.getAttribute("it"); if(it.hasNext()) { pageContext.setAttribute(var, it.next()); pageContext.setAttribute("it", it); return EVAL_BODY_AGAIN; }else { return EVAL_PAGE; } } }

SelectTag

package wangcong.tag; 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、定义下拉框的默认值 headkey headval * 4、下拉框加载数据 items * 5、属性值接受数据库中保存的value值 被选中的值 selectedval * * 属于展示的ui标签,要展示内容 * @author 10570 * */ public class SelectTag extends BodyTagSupport{ private static final long serialVersionUID = 8680576328606908002L; private String id; private String name; private List<Object> items = new ArrayList<>(); private String textkey; private String textval; private String headkey; private String headval; 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 getHeadkey() { return headkey; } public void setHeadkey(String headkey) { this.headkey = headkey; } public String getHeadval() { return headval; } public void setHeadval(String headval) { this.headval = headval; } public String getSelectedval() { return selectedval; } public void setSelectedval(String selectedval) { this.selectedval = selectedval; } @Override public int doStartTag() throws JspException { JspWriter out = pageContext.getOut(); try { //对你想展现在页面上的html代码进行拼接 out.print(toHTML()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return super.doStartTag(); } //拼接标签代码 private String toHTML() throws Exception, Exception { StringBuilder sb = new StringBuilder();//更快 sb.append("<select id='"+id+"' name='"+name+"'>"); //加载类似于下拉框默认显示的 请选择 //判定是否有值 if(!(headkey == null || "".equals(headkey) || headval == null || "".equals(headval))) { sb.append("<option selected value='"+headkey+"'>"+headval+"</option>"); } String val = "";//写option value 的 String html = "";//写在option标签体的 展示看 //循环打印数据 items = value for (Object obj : items) { //根据反射读写属性: //获取对象:obj.getClass() //获取对象的指定属性 textkey变量 → 对象的属性名(textval同理) //打开权限 //接收对应的属性值 //底层代码写法: Field f = obj.getClass().getDeclaredField(textkey); f.setAccessible(true); val = (String) f.get(obj); f = obj.getClass().getDeclaredField(textval); f.setAccessible(true); html = (String) f.get(obj); //第三方工具包写法:(commons-beanutils-1.8.0 和 commons-logging) // val = (String) PropertyUtils.getProperty(obj, textkey); // html = (String) PropertyUtils.getProperty(obj, textval); //考虑如果是修改页面时,下拉框回选数据库所存储的值 也就是默认选中数据库所存储的值 if(val.equals(selectedval)) { sb.append("<option selected value='"+val+"'>"+html+"</option>"); }else { sb.append("<option value='"+val+"'>"+html+"</option>"); } } sb.append("</select>"); return sb.toString();//返回拼接的值 } }

z.tld

<?xml version="1.0" encoding="UTF-8" ?> <taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1"> <description>onlyK 1.1 core library</description> <display-name>onlyK core</display-name> <tlib-version>1.1</tlib-version> <short-name>c</short-name> <uri>/onlyK</uri> <!-- set --> <tag> <name>set</name> <tag-class>wangcong.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> <!-- out --> <tag> <name>out</name> <tag-class>wangcong.tag.OutTag</tag-class> <body-content>JSP</body-content> <attribute> <name>value</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> <!-- if --> <tag> <name>if</name> <tag-class>wangcong.tag.IfTag</tag-class> <body-content>JSP</body-content> <attribute> <name>flag</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> <!-- foreach --> <tag> <name>foreach</name> <tag-class>wangcong.tag.ForeachTag</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> <!-- select --> <!-- 以 select 为例 --> <tag> <name>select</name> <tag-class>wangcong.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>headkey</name> <required>false</required> <rtexprvalue>false</rtexprvalue> </attribute><attribute> <name>headval</name> <required>false</required> <rtexprvalue>false</rtexprvalue> </attribute> <attribute> <name>selectedval</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>

index.jsp

<%@page import="com.wangcong.Test1"%> <%@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="/onlyK" 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>Insert title here</title> </head> <body> <z:set var="name" value="zs"></z:set> <z:out value="${name}"></z:out> <z:if flag="true">lx</z:if> <z:if flag="false">ww</z:if> <% List list=new ArrayList(); list.add(new Test1("1", "王聪")); list.add(new Test1("2", "王聪2")); list.add(new Test1("3", "王聪3")); pageContext.setAttribute("teas", list); %> <z:foreach var="t" value="${teas}"> ${t.id},${t.name}<br> </z:foreach> <h2>新增查询下拉框</h2> <z:select textkey="id" items="${teas }" textval="name"></z:select> <z:select headkey="-1" headval="请选择" textkey="id" items="${teas }" textval="name"></z:select> <h2>修改页面下拉框</h2> <z:select textkey="id" items="${teas }" textval="name" selectedval="王聪"></z:select> </body> </html>

测试结果如下:


最新回复(0)