开发者

How to access a session attribute using a dynamic name?

开发者 https://www.devze.com 2023-03-22 03:28 出处:网络
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 i

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.


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}
0

精彩评论

暂无评论...
验证码 换一张
取 消