自定義標籤的使用

20111109學習總結:

1、帶屬性的自定義標籤

1)控制標籤體循環輸出指定次數

在標籤處理類中添加屬性變量及其setter方法

private int times;

public void doTag() throws JspException, IOException {

JspFragment jf = this.getJspBody();

for(int i=0; i<times; i++){

jf.invoke(null);

}

}

public void setTimes(int times) {

this.times = times;

}

tld文件中增加屬性描述<attribute></attribute>

<attribute>

<name>times</name>

<required>true</required>

<rtexprvalue>true</rtexprvalue>

</attribute>

演示<trexprvalue>true</rtexprvalue>

<class3g:mySimpleTag5 times="<%=3+1 %>">

aaaaaaaaa<br>

</class3g:mySimpleTag5>

2)解釋傳參時類型轉換問題,並以Data數據的傳遞演示非基本數據類型的參數傳遞

在標籤處理類中添加Data類型成員及其setter方法

private Date date;

public void setDate(Date date) {

this.date = date;

}

tld中添加屬性描述

<attribute>

<name>date</name>

<required>true</required>

<rtexprvalue>true</rtexprvalue>

<type>java.util.Date</type>

</attribute>

jsp中調用

<class3g:mySimpleTag5 times="3" date="<%=new Date() %>">

xxxxxxxx

</class3g:mySimpleTag5>

2、標籤案例-開發防盜鏈標籤

盜鏈是指服務提供商自己不提供服務的內容,通過技術手段繞過其它有利益的最終用戶界面(如廣告),直接在自己的網站上向最終用戶提供其它服務提供商的服務內容,騙取最終用戶的瀏覽和點擊率。受益者不提供資源或提供很少的資源,而真正的服務提供商卻得不到任何的收益。

解決途徑之一——限制引用頁

這種防盜鏈原理是,服務器獲取用戶提交信息的網站地址,然後和真正的服務端的地址相比較,如果一致則表明是站內提交,或者爲自己信任的站點提交,否則視爲盜鏈。

目標:要開發的標籤

<class3g:referer site="http://drinkeye:8080" page="/index.jsp"/>

site:受信任站點,只允許次站點的請求

page:正確的鏈接頁面,發現盜鏈後將其自動轉入此頁面

步驟

1) 標籤處理類

public void doTag() throws JspException, IOException {

PageContext pageContext = (PageContext) this.getJspContext();

HttpServletRequest request = 

(HttpServletRequest) pageContext.getRequest();

HttpServletResponse response = 

(HttpServletResponse) pageContext.getResponse();

String referer = request.getHeader("referer");

System.out.println(request.getContextPath());

if(referer==null | !referer.startsWith(site)){

//判斷是否盜鏈

//根據page屬性值,講鏈接重定向指訪問被盜鏈內容的正確頁面

String contextPath = request.getContextPath();

if(page.startsWith(contextPath)){

response.sendRedirect(page);

}else if(page.startsWith("/")){

response.sendRedirect(contextPath + page);

}else{

response.sendRedirect(contextPath + "/" + page);

}

throw new SkipPageException();

}

}

2) 描述文件

3) 在內容頁面使用標籤

2、標籤案例-<c:if>標籤

標籤功能:

<class3g:if exp="${psw==null }">

user == null <br>

</class3g:if>

    

<%

     session.setAttribute("user","Tom");

%>    

<class3g:if exp="${user!=null }">

user != null <br>

</class3g:if>

處理類

public class MyIfTag extends SimpleTagSupport {

private boolean exp;

public void setExp(boolean exp) {

this.exp = exp;

}

public void doTag() throws JspException, IOException {

if(exp){

JspFragment jf = this.getJspBody();

jf.invoke(null);

}

}

}

3、標籤案例if else 標籤

<class3g:choose >

     <class3g:when exp="${user!=null }">

     aaaaaaaaaa

     </class3g:when>

     <class3g:otherwise>

     bbbbbbbbbbbbbbb

     </class3g:otherwise>

</class3g:choose>

步驟:

編寫choose標籤,無屬性,但有一個成員invoked,要爲其編寫settergetter方法,注意doTag中需要輸出標籤體

編寫子標籤when標籤,有boolean屬性exp

編寫子標籤otherwise標籤,無屬性,無成員變量


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章