How to get session attribute with a dynamic key in EL?
Asked Answered
A

2

23

If I set session like this:

<% 
session.setAttribute("taintedAttribute", "what ever we want");
%>

normally we can get session variable like this in EL

${sessionScope.taintedAttribute }

But how about if I want to do like this

<% 
String name = "taintedAttribute";
//session.setAttribute(name, "what ever we want");
session.getAttribute(name);
%>

Then how can we call it in EL?

Can EL get something like ${sessionScope.---dynamic name ---}?

If I do this:

<c:set var="name" value="taintedAttribute" />
<c:out value="${sessionScope.[name]}"/>

the name will be replaced by taintedAttribute as the same as this line

${sessionScope.taintedAttribute}

Is that possible? How can I do that?

Ancohuma answered 29/11, 2011 at 10:29 Comment(4)
how about not writing the java code in scriptlets and doing it all server side, maintaining MVC as much as possible.Whalen
i wanted to use only jstl in the jsp pages. That is why i ask how to do this. hehe. i need this code to check on this session, to display something in jsp.Ancohuma
@NurAini: The point is, you're not supposed to change the application state (this includes session attributes) in JSP at all. Whether it's using scriptlets or JSTL.Messroom
I am sorry. Its not that i wanted to change any of the application state.. I just wanted to check whether that session attribute exist or not.. I have edit the question because i made a mistake. I actually want something like session.getAttribute(name) in jstl.Ancohuma
P
30
<c:set var="name" value="taintedAttribute" />
<c:out value="${sessionScope.[name]}"/>

You were close. Remove the period.

<c:set var="name" value="taintedAttribute" />
<c:out value="${sessionScope[name]}"/>

See also:

Phraseologist answered 30/11, 2011 at 3:49 Comment(0)
H
2

Look at http://www.java2s.com/Code/Java/JSTL/JSTLSetVariablesScope.htm

<c:set var="test" value="Session Level Value"
    scope="session" />
<c:out value="${sessionScope.test}" />
Holmes answered 29/11, 2011 at 10:35 Comment(1)
Hi thank you for the reply, i am sorry i made a mistake in the code. I have editted the question and commented the line that is wrong. I actually wanted to write in jstl something like session.getAttribute(name). is that something that can be done in jstl?Ancohuma

© 2022 - 2024 — McMap. All rights reserved.