Jsp自定义标签

Tld文件:
<taglib>
   <tlib-version>1.0</tlib-version>
   <jsp-version>1.2</jsp-version>
   <short-name>mytag</short-name>
   <!-- 引用此tld文件的uri路径 -->
   <uri>www.ihome.com</uri>
   <tag>
    <!-- 标签名为helloworld-->
      <name>helloworld</name>
    <!-- 标签处理类 -->
      <tag-class>com.yd.mytag.HelloWorldTag</tag-class>
      <body-content>empty</body-content>
      <attribute>
     <!-- 传入标签的参数值 -->
      <name>flag</name>
     <!--  当为true则为必须属性-->
      <required>true</required>
       <rtexprvalue>true</rtexprvalue>
      </attribute>
   </tag>
</taglib>

jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!-- 引入tld文件
有两种方式,①:根据uri名字引用tld文件
                    ②:根据web配置,例如<%@ taglib uri="/tld/helloworld" prefix="mytag"%>
                    这里采用的是uri方式
-->

<%@ taglib uri="www.ihome.com" prefix="mytag"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>MyJSP</title>    
  </head>
 
  <body>
    <h1>自定义标签:</h1>
     <br>
     <br>
     <!-- mytag为标签前缀  hellworld为标签名  flag为tld文件定义的必须传递的属性 -->
     <mytag:helloworld flag="1"></mytag:helloworld>
     <br>
  </body>
</html>

web配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
     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-app_2_5.xsd">
 
  <jsp-config>
       <taglib>
         <taglib-uri>/tld/helloworld</taglib-uri>
         <taglib-location>/WEB-INF/tlds/helloworld.tld</taglib-location>
     </taglib>
  </jsp-config>
 
</web-app>

Java文件:
package com.yd.mytag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.TagSupport;
/**
*
* @author iHome
*
*/
public class HelloWorldTag extends TagSupport {

     private static final long serialVersionUID = 3174234039143531070L;
     private String flag ;

     public String getFlag() {
          return flag;
     }

     public void setFlag(String flag) {
          this.flag = flag;
     }

     @Override
     public int doStartTag() throws JspException {

          return EVAL_BODY_INCLUDE;

     }

     @Override
     public int doEndTag() throws JspException {
          String xx ="";
          if("1".equals(flag))
               xx = "有道词典";
          try {
               pageContext.getOut().write("Hello World!"+xx);

          } catch (IOException ex) {

               throw new JspTagException("错误");

          }

          return EVAL_PAGE;

     }

}



见附件

你可能感兴趣的:(jsp 自定义标签)