【问题标题】:How to access a request attribute set by a servlet in JSP?如何访问 JSP 中 servlet 设置的请求属性?
【发布时间】:2012-06-09 12:50:12
【问题描述】:

我正在尝试检索由 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 和目标页面)中传递一个参数,效果会非常好。

【问题讨论】:

    标签: java jsp servlets el


    【解决方案1】:

    您是否尝试过使用表达式标签?

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

    【讨论】:

    • 我考虑过使用它,但如果可能的话,我更喜欢使用 ${sth} 约定。
    • 不推荐使用scriptlet。
    【解决方案2】:

    它已经在默认的 EL 范围内可用,所以只需

    ${attrib}
    

    应该这样做。

    如果你想显式指定范围(EL会依次搜索页面、请求、会话和应用范围,寻找匹配属性名的第一个非空属性值),那么你需要通过范围来引用它而是映射,请求范围为 ${requestScope}

    ${requestScope.attrib}
    

    这仅在您可能在页面范围内具有完全相同名称的属性时才有用,否则会获得优先权(但这种情况通常表明设计不佳)。

    另见:

    【讨论】:

    • 如何在 CSS 文件中获得相同的属性?
    【解决方案3】:

    也许EL 语法和scriptlet 语法之间的比较会帮助您理解这个概念。

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

    你需要告诉request attributerequest parameter

    【讨论】:

    • 谢谢!这有助于我们在不知不觉中认为 requestScope 类似于请求对象本身,而不是 request.getAttribute()。
    【解决方案4】:

    如果范围是请求类型,我们在请求中使用request.setAttribute(key,value)设置属性,在jsp中使用${requestScope.key}检索。

    【讨论】:

      猜你喜欢
      • 2011-06-22
      • 1970-01-01
      • 2018-03-12
      • 1970-01-01
      • 1970-01-01
      • 2014-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多