簡體   English   中英

從“定制標記”中從JSP獲取應用程序字段

[英]Get application field from JSP from Custom Tag

我必須計算頁面的訪問量,但是當計數為奇數時,我不應該打印計數,而必須從自定義標簽執行此操作。 我無法通過自定義標記調用字段計數。

這是我的代碼:

索引jsp文件

<%
    Integer count = (Integer)application.getAttribute("numberOfVisits");

    if (count == null || count == 0)
    {
        out.println("Welcome!");
        count = 1;
    }
    else
    {
        out.println("Welcome back");
        count++;
    }
    application.setAttribute("numberOfVisits", count);
%>
<%@ taglib uri="/WEB-INF/mytags.tld" prefix="c" %>
<c:counter></c:counter>
<%=count%>

自定義標簽類:

public int doEndTag() throws JspException{

    try
    {
        int count = application.getAttribute("numberOfVisits") // wrong
        if (count % 2 != 0) return EVAL_PAGE;
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }      
    return SKIP_PAGE;
}

}

請找到以下答案,該答案使用自定義標簽打印奇數。

1)創建Tag處理程序類要創建Tag Handler,我們將繼承TagSupport類並覆蓋其方法doStartTag()。要為jsp寫入數據,我們需要使用JspWriter類。

PageContext類提供了getOut()方法,該方法返回JspWriter類的實例。 TagSupport類默認提供pageContext的實例。

package com.test;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;

public class CountTagHandler extends TagSupport{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public int doStartTag() throws JspException {
        JspWriter out=pageContext.getOut();
        try{
            Integer attribute = (Integer)pageContext.getAttribute("numberOfVisits", PageContext.APPLICATION_SCOPE);

            //Print the value only if it is even
            if(attribute != null && attribute % 2 == 0) {
                out.print(attribute);
            }
        }catch(Exception e){System.out.println(e);}
        return SKIP_BODY;
    }

}

2)創建TLD文件標簽庫描述符(TLD)文件包含標簽和標簽處理程序類的信息。 它必須包含在WEB-INF目錄中。

文件:mytags.tld

<?xml version="1.0" encoding="ISO-8859-1" ?>  
<!DOCTYPE taglib  
        PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"  
    "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">  

<taglib>  

  <tlib-version>1.0</tlib-version>  
  <jsp-version>1.2</jsp-version>  
  <short-name>simple</short-name>  
  <uri>http://tomcat.apache.org/example-taglib</uri>  

<tag>  
<name>count</name>  
<tag-class>com.test.CountTagHandler</tag-class>  
</tag>  
</taglib>  

3)創建JSP文件讓我們使用jsp文件中的標簽。 在這里,我們直接指定tld文件的路徑。 但是建議使用uri名稱代替tld文件的完整路徑。 稍后我們將了解uri。

它使用taglib指令來使用tld文件中定義的標簽。 從jsp或項目的其他任何地方,設置“ numberOfVisits” 例如: jsp file1

<%! static int count = 0;  %>
<%
    application.setAttribute("numberOfVisits", count++);
%>
<a href="second.jsp">Custom link</a>

這是第二個jsp文件:

<h3>Using tag</h3>
<%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>

Application count: <m:count/>

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM