简体   繁体   中英

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} . 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:

<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.

It's available in the default EL scope already, so just

${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

${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.

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

You need to tell request attribute from request parameter .

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM