简体   繁体   English

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

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

I'm trying to retrieve attribute values set by a servlet in a JSP page, but I've only luck with parameters by ${param} .我试图在 JSP 页面中检索由 servlet 设置的属性值,但我只对${param}参数感到幸运。 I'm not sure about what can I do different.我不确定我能做些什么不同。 Maybe its simple, but I couldn't manage it yet.也许它很简单,但我还不能管理它。

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);
}

In the JSP I have been trying to retrieve the "attribValue", but without success:在 JSP 中,我一直试图检索“attribValue”,但没有成功:

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

If I pass a parameter through all the process (invoking page, servlets and destination page), it works quite good.如果我在整个过程(调用页面、servlet 和目标页面)中传递一个参数,它会工作得很好。

It's available in the default EL scope already, so just它已经在默认的 EL 范围内可用,所以只需

${attrib}

should do.应该做。

If you like to explicitly specify the scope (EL will namely search the page, request, session and application scopes in sequence for the first non-null attribute value matching the attribute name), then you need to refer it by the scope map instead, which is ${requestScope} for the request scope如果您想明确指定范围(EL 将依次搜索页面、请求、会话和应用程序范围,以查找与属性名称匹配的第一个非空属性值),那么您需要通过范围映射来引用它,这是请求范围的${requestScope}

${requestScope.attrib}

This is only useful if you have possibly an attribute with exactly the same name in the page scope which would otherwise get precedence (but such case usually indicate poor design after all).这仅在页面范围内可能具有完全相同名称的属性时才有用,否则将获得优先级(但这种情况通常表明设计不佳)。

See also:也可以看看:

Maybe a comparison between EL syntax and scriptlet syntax will help you understand the concept.也许比较EL语法和scriptlet语法会帮助你理解这个概念。

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

You need to tell request attribute from request parameter .您需要从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