How to access a request attribute set by a servlet in JSP?
Asked Answered
G

4

28

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.

Gut answered 5/6, 2012 at 13:39 Comment(0)
A
36

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:

Audry answered 5/6, 2012 at 14:13 Comment(1)
And how can I get the same attribute in a CSS file?Chartist
E
10

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.

Enright answered 28/1, 2015 at 3:29 Comment(1)
Thanks! This helps, unknowingly we think requestScope is similar to request object itself, rather than request.getAttribute( ).Inane
P
3

have you tried using an expression tag?

<%= request.getAttribute("attrib") %>
Pray answered 5/6, 2012 at 13:56 Comment(2)
I've considered using it, but I prefer using the ${sth} convention, if it would be possible.Gut
scriptlet is not recommended.Enright
C
3

If the scope is of request type, we set the attribute using request.setAttribute(key,value) in request and retrieve using ${requestScope.key} in jsp .

Camire answered 9/3, 2019 at 14:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.