Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a session attribute using a dynamic name?

Tags:

java

jstl

el

This is a very simplified example of the problem I'm having trying to reference a session bean by constructing the name of the attribute dynamically using JSTL/EL. The name of the session attribute is "userBean" which has a property "name" with corresponding getter/setter.

This works<br>
User: ${userBean.name}<br>

<c:set var="userBeanName">${userBean}.name</c:set><br>

This does not work<br>
User:  ${userBeanName}<br>

the results are:

This works
User: ACOSTA SALES COMPANY

This does not work
User: 000101.name

The second one is calling the toString() method of my userBean class and concatenating that + ".name".

Surely there is a very simple answer to this; however, I can't figure it out with my limited knowledge.

like image 771
Chris Horwedel Avatar asked Jan 22 '26 09:01

Chris Horwedel


1 Answers

The code example is confusing and does not relate to the question as stated in the title and the 1st paragraph. So, I'll ignore the code example and only answer the title:

How to access a session attribute using a dynamic name?

You can use ${sessionScope} to get a mapping of all session attributes. You can use the brace notation to evaluate a variable as attribute name ${sessionScope[attributeName]}.

So, this should do:

<c:set var="attributeName" value="userBean" />

User name: ${sessionScope[attributeName].name}
like image 117
BalusC Avatar answered Jan 24 '26 23:01

BalusC