简单自定义标签

来源:互联网 发布:plugins.js是什么 编辑:程序博客网 时间:2024/05/29 16:27
 

第一步:编写一个实现tag接口的实现类

view plaincopy to clipboardprint?
  1. //控制标签体输出   
  2. public class SimpleTag1 extends SimpleTagSupport {  
  3.   
  4.     @Override  
  5.     public void doTag() throws JspException, IOException {  
  6.         JspFragment jf = this.getJspBody();  
  7.   
  8.         //循环输出标签体内容   
  9. //      for(int i=0; i<10; i++){  
  10. ////            jf.invoke(null);   
  11. //          jf.invoke(this.getJspContext().getOut());  
  12. //      }   
  13.           
  14.         //忽略本标签之后的jsp代码   
  15.         //throw new SkipPageException();  
  16.           
  17.           
  18.         //大小写转换        
  19.         StringWriter sw = new StringWriter();  
  20.         jf.invoke(sw);  
  21.           
  22.         String content = sw.getBuffer().toString();  
  23.           
  24.         content = content.toUpperCase();  
  25.           
  26.         JspWriter out = this.getJspContext().getOut();  
  27.         out.write(content);  
  28.           
  29.     }  
  30.   
  31. }  


第二步:在tld文件中对标签处理器类进行描述(放在WEB-INF目录下)

可以复制并修改D:\apache-tomcat-6.0.32\webapps\examples\WEB-INF\jsp2中的xml代码
class3g.tld

view plaincopy to clipboardprint?
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2.   
  3. <taglib xmlns="http://java.sun.com/xml/ns/j2ee"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"  
  6.     version="2.0">  
  7.       
  8.     <description>there are custom tags of class3g</description>  
  9.     <tlib-version>1.0</tlib-version>  
  10.     <short-name>class3g</short-name>  
  11.     <uri>http://www.class3g.com</uri>  
  12.       
  13.     <tag>  
  14.         <description>demo1</description>  
  15.         <name>simpleTag1</name>  
  16.         <tag-class>class3g.web.simpleTag.SimpleTag1</tag-class>  
  17.         <body-content>scriptless</body-content>  
  18.     </tag>  
  19.        
  20. </taglib>  

第三步:在jsp中导入并使用自定义标签

view plaincopy to clipboardprint?
  1. <pre class="html" name="code"><pre class="html" name="code"><pre class="html" name="code"><%@taglib uri="http://www.class3g.com" prefix="class3g" %>  
  2.  <class3g:simpleTag1><h1>我在这!hello!</h1></class3g:simpleTag1>   
  3.    xxxxxxxxxxxxxxxxxxxThis is my JSP page. <br>