JSP自定義標籤之三:為標籤新增屬性

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

<%@ taglib uri="WEB-INF/tlds/testlib.tld" prefix="yzj" %>

 

<html>

    <head>    

        <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />

        <title>自定義標籤簡單示例</title>

    </head>                     

    <body>

        <p>這裡是正文內容</p>

        <yzj:copyright copyOwner="顏志軍" startYear="2008"/>

    </body>

</html>

 

當然,如果像上述JSP檔案那樣來使用我們自定義的版權標籤,還必須修改tld檔案中的標籤說明,具體地說就是需要為標籤說明屬性copyOwner與startYear。修改完成之後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>

            <name>copyOwner</name>

        </attribute>

        <attribute>

            <name>startYear</name>

        </attribute>

    </tag>

</taglib>

 

很容易想到,上述修改不會是全部的工作,決定標籤顯示資訊的自定義標籤處理程式也必須做出相應的修改才最終會實現通過標籤屬性設定部分資訊的功能。標籤處理程式處理標籤屬性的方式與JavaBeans是完全一樣的,即可以通過為標籤處理程式新增名稱為“set+屬性名”的方法取得標籤中相應屬性所設定值。

修改之後的標籤處理程式如下:

package com.yanzhijun;

 

import java.io.*;

import javax.servlet.jsp.*;

import javax.servlet.jsp.tagext.*;

 

public class CopyRightTag extends TagSupport

{                           

    private String copyOwner;

    private String startYear;

   

    public void setCopyOwner(String  copyOwner)

    {

        this.copyOwner = copyOwner;

    }                              

   

    public void setStartYear(String  startYear)

    {

        this.startYear = startYear;

    }

   

    public int doEndTag()

    {

        try

        {  

            String copyPre = new String(copyOwner.getBytes("ISO8859_1"), "GB2312")  +  "版權所有&nbsp;&copy" + startYear;                         

            String info = new String(copyPre.getBytes("GB2312"), "ISO8859_1");

            pageContext.getOut().println(info); 

        }

        catch(IOException e){}

        return EVAL_PAGE;

    }   

        

相關文章