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

自定义JSP标签

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

自定义JSP标签

生命标签图:
自定义JSP标签

1、标签的特点

1.1 标签分两种类型:数据标签和控制标签。
数据标签的特点:存储数据,没有任何的页面效果。标签 set
控制标签的特点:控制的对象是标签体。标签 if foreach

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

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

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

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

2.4介绍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>DZY 1.1 core library</description>
  <display-name>DZY core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>c</short-name>
  <uri>http://DZY</uri><!--uri的地址调用  -->

 <tag>
  <!--填写的是标签库中的标签名  -->
    <name>catch</name>
    <!--标签对应后台助手类  -->
    <tag-class>org.apache.taglibs.standard.tag.common.core.CatchTag</tag-class>
    <!-- 标签类别 -->
    <body-content>JSP</body-content>
    <attribute>
    <!--自定义标签中属性  -->
        <name>var</name>
        <!-- 属性值是否必填 -->
        <required>false</required>
        <!--是否支持表达式/ognl表达式  -->
        <rtexprvalue>false</rtexprvalue>
    </attribute>
  </tag>

3、演示自定义JSP标签

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

3.1 set和out的标签操作:
out操作:

package com.DZY.jsp;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
/**
 * out类
 * @author Aromanic150
 *
 */
public class OutDemo extends BodyTagSupport {
public Object getValue() {
        return value;
    }
    public void setValue(Object value) {
        this.value = value;
    }
    private Object value;
    @Override
    public int doStartTag() throws JspException {
         JspWriter out=pageContext.getOut();
         try {
            out.write(value.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            throw new RuntimeException(e);
        }
        return SKIP_BODY;
    }
}

set操作:

package com.DZY.jsp;

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

/**
 * set类
 * 
 * @author Aromanic150
 *
 */
public class SetDemo extends BodyTagSupport {
 private static final long serialVersionUID = -123L;
 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);// 将值存入pageContext
  return SKIP_BODY;
 }
}

set和out在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>DZY 1.1 core library</description>
  <display-name>DZY core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>c</short-name>
  <uri>http://DZY.set</uri><!--uri的地址调用  -->
<!-- OUT标签 -->
 <tag>
    <name>out</name>
    <tag-class>com.DZY.jsp.OutDemo</tag-class>
    <body-content>empty</body-content>
 <attribute>
     <name>value</name>
     <required>true</required>
     <rtexprvalue>true</rtexprvalue>
 </attribute>
 </tag>

   <!-- SET标签 -->
 <tag>
   <name>set</name>
   <tag-class>com.DZY.jsp.SetDemo</tag-class>
   <body-content>JSP</body-content>
   <attribute>
      <name>var</name>
      <required>false</required>
      <rtexprvalue>true</rtexprvalue>
   </attribute>
    <attribute>
      <name>value</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
   </attribute>
   </tag>

   </taglib>

在JSP中操作:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
  <%@  taglib   uri="http://DZY.set"   prefix="k"%>//导入地址
<!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>
 <k:set value="你好"  var="kin"></k:set>
 <k:out value="${kin }"/>
</body>
</html>

显示结果:
自定义JSP标签

3.2 自定义if标签
If的操作:

package com.DZY.jsp;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
/**
 * if类
 * @author Aromanic150
 *
 */
 public class IfDemo   extends   BodyTagSupport {
    private    boolean  test;
    public boolean isTest() {
  return test;
 }
    public void setTest(boolean test) {
  this.test = test;
 } 
    @Override
    public int doStartTag() throws JspException {
     if(!test) {
      return   SKIP_BODY;//不显示标签中间的内容
     }
     return EVAL_BODY_INCLUDE;//显示标签的内容
    }  
}

tld的操作:
都在一个tld里,我就不放全部了。

<!-- if标签 -->
 <tag>
   <name>if</name>
   <tag-class>com.DZY.jsp.IfDemo</tag-class>
   <body-content>JSP</body-content>
   <attribute>
      <name>test</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
   </attribute>
   </tag>

在JSP的操作:

 <k:if test="true">你好吗?</k:if>
<k:if test="false">不好</k:if>

显示结果:自定义JSP标签

3.3 自定义Foreach标签
Foreach操作:

package com.DZY.jsp;

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

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.swing.text.html.HTML.Tag;
public class ForeachDemo extends BodyTagSupport{
 //集合
    private List<Object> items;
    //变量的名称
     private String var;
    public List<Object> getItems() {
        return items;
    }
    public void setItems(List<Object> items) {
        this.items = items;
    }
    public String getVar() {
        return var;
    }
    public void setVar(String var) {
        this.var = var;
    }

     @Override
    public int doStartTag() throws JspException {
        // TODO Auto-generated method stub
         if(items==null||items.size()==0) {
             return SKIP_BODY;
         }
         else {
             Iterator<Object> i=items.iterator();
             pageContext.setAttribute("s", i);
             //第一次给变量进行赋值
             pageContext.setAttribute(var, i.next());
        return EVAL_BODY_INCLUDE;
      } 
         }

     @Override
    public int doAfterBody() throws JspException {
         Iterator<Object> it=(Iterator<Object>)pageContext.getAttribute("s");
     while(it.hasNext()) {
         //如何将循环读取出来的数据,显示在页面上
         pageContext.setAttribute(var, it.next());
         return EVAL_BODY_AGAIN;
     }
        return SKIP_BODY;
    }
    }

tid的操作:

   <!--foreach标签  -->
<tag>
 <name>foreach</name>
 <tag-class>com.DZY.jsp.ForeachDemo</tag-class>
 <body-content>JSP</body-content>
 <attribute>
 <name>items</name>
 <required>true</required>
 <rtexprvalue>true</rtexprvalue>
 </attribute>

<attribute>
 <name>var</name>
 <required>true</required>
 <rtexprvalue>true</rtexprvalue>
 </attribute>
</tag>

Student类

package com.DZY.jsp;

public class Student {
 private String sid;
 private String sname;
 public Student() {
 }
 public Student(String sid, String sname) {
  this.sid = sid;
  this.sname = sname;
 }
 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;
 }
 }

jsp代码:

  List   kin=new  ArrayList();
  kin.add(new Student("1","qqq"));
  kin.add(new Student("2","www"));
  kin.add(new Student("3","eee"));
  kin.add(new Student("4","rrr"));
  kin.add(new Student("5","ttt"));
  request.setAttribute("kin", kin);
%>
<k:foreach items="${kin}" var="as">
${as.sid} ,   ${as.sname}<br>
</k:foreach>

3.4 自定义Select 标签
Select 操作:

package com.DZY.jsp;

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

public class SelectDemo 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(toHTML());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return super.doStartTag();
    }
     /**
     * 拼接出下拉列表所对应的select的html代码 
     * <select id='' name=''>
     *  <option value='-1'selected>=======请选择======</option>
     *   </select>
     */
    private String toHTML() throws Exception {
        StringBuilder sb = new StringBuilder();
        sb.append("<select id='" + id + "' name='" + name + "'>");
        if (headTextKey == null || "".equals(headTextKey) || headTextVal == null || "".equals(headTextVal)) {
            sb.append("<option value='" + headTextKey + "' selected>" + headTextVal + "</option>");
        }
        String val;
        String html;
        for (Object obj : items) {
            // 要让学生的id存入数据库,让学生的名字展示在jsp页面
            // <option value='s001'>ls</option>
            // obj sid sname
            Field textKeyField = obj.getClass().getDeclaredField(textKey);
            textKeyField.setAccessible(true);
            val = (String) textKeyField.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();
    }
}

tid的操作

<!--select标签  -->
<tag>
        <name>select</name>
        <tag-class>com.DZY.jsp.SelectDemo</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>true</rtexprvalue>
        </attribute>
    </tag>

jsp代码

<%
  List   kin=new  ArrayList();
  kin.add(new Student("1","qqq"));
  kin.add(new Student("2","www"));
  kin.add(new Student("3","eee"));
  kin.add(new Student("4","rrr"));
  kin.add(new Student("5","ttt"));
  request.setAttribute("kin", kin);
%>
  <k:select textVal="sname" items="sid" textKey="${kin }"></k:select>
 <k:select headTextKey="-1" headTextVal="===请选择学生===" itmes="${kin}"    textKey="sid"   textVal="sname"></k:select>
相关标签: 自定义JSP标签