自定義標記庫開發入門篇

JSP中開發自定義標籤步驟:

以在JSP頁面輸出"hello world"爲例:

第一步,標籤底層實現.

代碼如下:

  1. package com.dadao.tag;
  2. import java.io.IOException;
  3. import javax.servlet.jsp.JspException;
  4. import javax.servlet.jsp.tagext.SimpleTagSupport;
  5. public class HelloWorldTag extends SimpleTagSupport {
  6.     @Override
  7.     public void doTag() throws JspException, IOException {
  8.         this.getJspContext().getOut().write("hello world");
  9.     }
  10.     
  11. }

第二步,撰寫標記庫的tld文件:

在/WEB-INF目錄下新建一個taglib/cy.tld文件.內容如下:

  1. <taglib xmlns="http://java.sun.com/xml/ns/j2ee"
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
  4.     version="2.0">
  5.    <description>oper tag  library</description>
  6.    <display-name>display text</display-name>
  7.    <tlib-version>1.0</tlib-version>
  8.    <short-name>cy</short-name>
  9.    <uri>http://mytaglib/chenyang</uri>
  10.    <tag>
  11.      <description>chenyang's custom display message tag</description>
  12.      <name>sayHello</name>
  13.      <tag-class>com.dadao.tag.HelloWorldTag</tag-class>
  14.      <body-content>empty</body-content>
  15.    </tag>
  16. </taglib>

第三步,在web.xml中的配置,

  1.   <jsp-config>
  2.     <taglib>
  3.         <taglib-uri>/WEB-INF/taglib/cy.tld</taglib-uri>
  4.         <taglib-location>http://mytaglib/chenyang</taglib-location>
  5.     </taglib>
  6.   </jsp-config>

第四步,撰寫JSP文件,代碼如下:

  1. <%@ page language="java"  pageEncoding="UTF-8"%>
  2. <%@ taglib prefix="cy" uri="http://mytaglib/chenyang" %>
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  4. <html>
  5.   <head>
  6.     <title>My JSP 'index.jsp' starting page</title>
  7.   </head>
  8.   <body> 
  9.     <cy:sayHello/>
  10.   </body>
  11. </html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章