j2ee自定義標籤的最簡單例子

瓜瓜東西發表於2014-07-10

總共需要四步

1 jsp  匯入自定義標籤

<%@ page language="java" import="java.util.*"  contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="WEB-INF/tlds/testlib.tld" prefix="yzj2" %>
 
<html>
    <head>    
        <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
        <title>自定義標籤簡單示例</title>
    </head>                     
    <body>
        <p>這裡是正文內容</p>
        <yzj2:copyright/>
    </body>
</html>

2 web-info/目錄下建立資料夾tags,tags下建立檔案testlib.tld,testib.tld檔案內容

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
 
<taglib>
    <tlibversion>1.0</tlibversion>
    <jspversion>1.1</jspversion>
    <shortname>yzj</shortname>
   
    <tag>
        <name>copyright</name>
        <tagclass>com.yanzhijun.CopyRightTag</tagclass>
        <bodycontent>empty</bodycontent>
        <attribute/>
    </tag>
</taglib>

3 寫上面的配置檔案需要的類

package com.yanzhijun;

import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
 
public class CopyRightTag extends TagSupport
{
    public int doEndTag()
    {
        try
        {  
            String copyPre = "版權所有2008";                        
            String info = new String(copyPre.getBytes(), "UTF-8");
            pageContext.getOut().println(copyPre);  
        }
        catch(IOException e){}
        return EVAL_PAGE;
    }   
}   

4 web.xml中進行引用,在tomcat啟動的時候會載入標籤的功能

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>tags</display-name>
  <jsp-config>
    <taglib>
      <taglib-uri>/testlib</taglib-uri>
      <taglib-location>/WEB-INF/tlds/testlib.tld</taglib-location>
    </taglib>
  </jsp-config>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>




相關文章