簡體   English   中英

如何訪問由 JSP 中的 servlet 設置的請求屬性?

[英]How to access a request attribute set by a servlet in JSP?

我試圖在 JSP 頁面中檢索由 servlet 設置的屬性值,但我只對${param}參數感到幸運。 我不確定我能做些什么不同。 也許它很簡單,但我還不能管理它。

public void execute(HttpServletRequest request, HttpServletResponse response) {

    //there's no "setParameter" method for the "request" object
    request.setAttribute("attrib", "attribValue");

    RequestDispatcher rd = request.getRequestDispatcher("/Test.jsp");
    rd.forward(request,response);
}

在 JSP 中,我一直試圖檢索“attribValue”,但沒有成功:

<body>
    <!-- Is there another tag instead of "param"??? -->
    <p>Test attribute value: ${param.attrib}
</body>

如果我在整個過程(調用頁面、servlet 和目標頁面)中傳遞一個參數,它會工作得很好。

它已經在默認的 EL 范圍內可用,所以只需

${attrib}

應該做。

如果您想明確指定范圍(EL 將依次搜索頁面、請求、會話和應用程序范圍,以查找與屬性名稱匹配的第一個非空屬性值),那么您需要通過范圍映射來引用它,這是請求范圍的${requestScope}

${requestScope.attrib}

這僅在頁面范圍內可能具有完全相同名稱的屬性時才有用,否則將獲得優先級(但這種情況通常表明設計不佳)。

也可以看看:

也許比較EL語法和scriptlet語法會幫助你理解這個概念。

  • param就像request.getParameter()
  • requestScope就像request.getAttribute()

您需要從request parameter告訴request attribute

您是否嘗試過使用表達式標簽?

<%= request.getAttribute("attrib") %>

如果范圍是請求類型,我們在請求中使用request.setAttribute(key,value)設置屬性request.setAttribute(key,value)並在 jsp 中使用${requestScope.key}檢索。

暫無
暫無

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

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