如何访问JSP中的servlet设置的请求属性?

问题描述 投票:19回答:4

我正在尝试在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
4个回答
25
投票

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

${attrib}

应该做。

如果您想明确指定范围(EL将按顺序搜索与属性名称匹配的第一个非null属性值的页面,请求,会话和应用程序范围),那么您需要通过范围映射来引用它,这是请求范围的${requestScope}

${requestScope.attrib}

这仅在页面范围中可能具有完全相同名称的属性时才有用,否则该属性将优先(但这种情况通常表示设计不佳)。

See also:


9
投票

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

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

你需要告诉request attributerequest parameter


2
投票

你试过用吗?

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

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.