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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Nur Aini
  • 393
  • 2
  • 5
  • 14
  • 3
    how about not writing the java code in scriptlets and doing it all server side, maintaining MVC as much as possible. – NimChimpsky Nov 29 '11 at 10:37
  • 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. – Nur Aini Nov 30 '11 at 02:32
  • @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. – millimoose Nov 30 '11 at 02:43
  • 1
    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. – Nur Aini Nov 30 '11 at 02:45

2 Answers2

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
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}" />
Stanislav Levental
  • 2,165
  • 1
  • 14
  • 28
  • 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? – Nur Aini Nov 30 '11 at 02:48