天天看點

JSP中自定義标記庫的使用(三)

 三、一個簡單的範例 

1、建立hello标簽:定義一個名為mytaglib的标簽庫,它包含一個簡單的hello标簽,這個标簽能夠将 

JSP頁面中所有的解析為字元串"hello". 

A、hello标簽的處理類: 

代碼 

public int doEndTag() throws JspException{ 

             try{ 

                      pageContext.getOut().print("hello"); 

                  }catch(Exception e){ 

                      throw new JspTagException(e.getMessage()); 

                  }                  return EVAL_PAGE;      }   

B、建立标簽庫描述檔案:.tld檔案存放位置;标簽庫名,标簽名,屬性,對應的處理類。 

C、web.xml中引入标簽庫: 

代碼 

... ... 

             /mytaglib 

            /WEB-INF/tld/mytaglib.tld 

... ...   

D、JSP頁面中引入标簽庫說明,并使用标簽: 

taglib指令中,prefix屬性值用作指代mytaglib标簽庫。 

四、另一個标簽 

1、建立一個能替換helloapp應用中JSP網頁的靜态文本的标簽,這個标簽名為message,它放在mytaglib标簽庫中。 

2、在hellowithtag2.jsp檔案中使用message标簽的代碼如下: 

當客戶通路hello.jsp網頁時,message标簽的處理類會根據屬性key的值從一個文本檔案中找到與key比對的字元串。假定這個字元串為“Hello”,然後将這個字元串輸出到網頁上。 

3、建立包含JSP網頁靜太文本的檔案 

messageresource.properties: 

hello.title=Title of hello.jsp 

hello.hello=hello 

4、 

代碼 

由<span style="color:red;">DispatcherServlet</span>類的init方法負責從靜态文本中讀取靜态文本,然後把它們裝載到Properties對象中,最後再把這個Properties對象作為屬性儲存到ServletContext中。   

5、DispatcherServlet類的init方法: 

代碼 

public void init(ServletConfig config) throws ServletException{ 

           super.init(config); 

           Properties ps=news Properties(); 

           SevletContext c.getServletContext(); 

           InputStream in=context.getResourceAsStream("/WEB-INF/messageresource"); 

           ps.load(in); 

           in.close(); 

            context.setAttribute("ps",ps); 

     }   

6、為保證在WEB應用啟動時就加載DispathcherServlet,應該在web.xml中配置這個Servlet時的設定load-on-startup屬性: 

dispacher 

mypack.DspacherServlet 

n dispatcher n mypack.DispatcherServlet n 1 7、建立MessageTag标簽處理類 

MessageTag包含一個成員變量key ,它與message标簽的屬性key 對應,在MessageTag 

中定義了getKey和setKey 方法。 

代碼 

   private String key=null; 

       public String getKey(){ 

              return this.key; 

      } 

        public void setKey(String key) 

              this.key=key; 

    } 

  在MessageTag的doEndTag方法中,首先從pageContext中讀取包含靜态文本的Properties對象: 

代碼 

Properties ps=(Properties)pageContext.getAttribute("ps",pageContext.APPLACTION_SCOPE);  然後從Properties對象中讀取key對應的靜态文本,最後輸出該文本: 

代碼 

String message=null; 

  message=(String)ps.get(key); 

  pageContext.getOut.print(message); 

  8、mytaglib庫中定義message标簽: 

代碼 

message 

     mypack.MessageTag 

    empty 

     produce message by key 

           key 

      true   

後記: 

1問題:在标簽處理類中,如何通路session範圍内的共享資料? 

選項: 

(B)在标簽處理類TagSupport類中定義了pageContext成員變量,先通過它的 

getSession()方法獲得目前的HttpSession對象,再調用HttpSession對 

象的getAttribute()方法。