2015-03-25 25 views
2

這是我的jsp頁面:角色了request.setAttribute JSP

  <!DOCTYPE html> 
    <html> 
    <head> 
     <meta charset="utf-8" /> 
     <title>Test EL</title> 
    </head> 
    <body> 
    <p> 

    <% 
    /* Creation */ 
    String[] animals = {"dog", "cat", "mouse", "horse"}; 
    request.setAttribute("animals" , animals); 
    %> 

    ${ animals[2] }<br /> 

</p> 
</body> 

我不明白的是:什麼是指令的工具: 「request.setAttribut」,我已經有表格聲明,我不明白爲什麼當我刪除該指令,我不能得到動物[2]價值..我在這裏想念什麼?!

+0

的「*着請詳細說明獲得動物[2]值*「。究竟發生了什麼? – 2015-03-25 02:35:20

+0

我在瀏覽器中顯示空白屏幕 – 2015-03-25 02:37:46

+0

我剛剛運行了您的代碼。我沒有看到任何錯誤。相反,它打印的是「鼠標」,這是實際的輸出。 – venky 2015-03-25 07:07:36

回答

0

${}這是一個JSP EL表達式。 EL只能引用範圍的變量而不是本地的變量。 作用範圍變量是指作爲屬性添加到可用的四個示波器中的任何一個,即pageContext,request,sessionapplication

在您的示例中,String[] animals本地變量,因此無法通過${}自行訪問。爲了使animals數組可用於JSP EL,它需要首先放入任何一個可用的作用域中。

因此,在您的示例中,以下是將數組放在request範圍內。

// restricted to current request cycle 
request.setAttribute("animals" , animals); 

您也可以根據您的應用需求使用以下任何一種。

// restricted to this JSP page 
pageContext.setAttribute("animals" , animals); 

// restrcited to this user's session 
session.setAttribute("animals" , animals); 

// available throughout the application 
application.setAttribute("animals" , animals); 

${animals[i]}從以下列順序在上述範圍中的任一個自動解析對象:第一,它看起來在pageContext,然後request,然後session,最後application

要覆蓋上述查找順序,範圍也可以被明確指定爲

${pageScope.animals[i]} 
${requestScope.animals[i]} 
${sessionScope.animals[i]} 
${applicationScope.animals[i]} 
0

加成拉維,如果你仍然想沒有這些屬性之一設置訪問數組,使用JSP表達標記來顯示:

Eg: <%=animals[2]%> <br/> 
0

正如它在ServletRequest documentationsetAttribute() Method的提及被用來存儲在請求中的屬性,從而可以在以後對其進行訪問。

${variable}是一個jsp EL,用於在您的web應用程序中輕鬆訪問這些存儲的數據,請查看JSP - Expression Language (EL)瞭解關於它的更多信息。

如果你是在你宣佈你的變量在同一個頁面,你能避免使用的setAttribute()和EL和打印使用out.print()這樣的變量結果:

<% out.println(animals[2]);%> 
相關問題