JSP自定义标签mytaglib

1、首先建立一个Web Project
2、在src中建立一个类(class),代码如下:
package com;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class HelloWorldTag extends TagSupport
{
 //标签开始时调用方法
 public int doStartTag()
 {
  try
  {
   JspWriter out = pageContext.getOut();
   out.println("标签开始:<font color=/"red/">hello!");
  }catch(Exception e)
  {
   System.out.print(e);
  }
  return EVAL_BODY_INCLUDE;
 }
 //标签结束时调用
 public int doEndTag()
 {
  try
  {
   JspWriter out = pageContext.getOut();
   out.print("标签结束");
  }catch(Exception e)
  {
   System.out.println(e);
  }
  return EVAL_PAGE;
 } 
}
 
 
3、自定义标签,如mytaglib.tlb
输入如下内容:
<?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">
    <tlib-version>1.0</tlib-version>
    <short-name>myTagLib</short-name>
    <uri>/myTag</uri>
    <tag>
        <name>helloTag</name>
  <tag-class>com.HelloWorldTag</tag-class>
  <body-content>empty</body-content>
    </tag>
</taglib>
4、web.xml中的部署
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
 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-app_2_4.xsd ">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <jsp-config>
  <taglib>
   <taglib-uri>/myTag</taglib-uri>
   <taglib-location>/WEB-INF/mytaglib.tld</taglib-location>
   </taglib>
  </jsp-config>

</web-app>
5、在JSP中调用,代码如下:
导入标签:<%@ taglib uri=" http://www.myjsp.org/mytaglib " prefix="mytag"%>
调用自定义标签:<mytag:helloWorld/>
 
下面为完整外码:
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@ taglib uri="/myTag" prefix="myTag" %>
<html>
  <head>
     <title>自定义标签示范</title>
  </head>
  <body>
  下面是应用这个简单的自定义标签的结果:<br>
  <myTag:helloTag/>
    </body>
</html>
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值