0

In PHP we can do the following with the help of Variable variables in PHP:

$privateVar = 'Hello!';
$publicVar = 'privateVar';
echo $$publicVar; // Hello!

Suppose we have the following chunk of Java code:

request.setAttribute("privateVar", "Hello!");
request.setAttribute("publicVar", "privateVar");

I've tried the following but an error occurs.

${${publicVar}}

Does anyone know how we can get value of privateVar via using only publicVar in JSP (JSTL)?

UPDATE 1:

I have a custom tag which allows to print a message if an object foo doesn't have a field bar. I know I must catch exceptions in the case but I don't want to handle ones in JSP. I want to do it only in CustomTag file.

<%-- JSP file --%>
<ctf:tagName varName="foo.bar" />

<%-- CustomTag file --%>
<%@ attribute name="varName" required="true" rtexprvalue="true"%>
<c:catch var="exception">
    <c:set var="valX" value="${${varName}}" scope="page"/>
</c:catch>
<c:if test="${exception != null}">Can't find getter for the VAR in the OBJ.</c:if>

UPDATE 2:

JB Nizet gave me the answer and the following works well! :)

<c:set var="privateVar" value="Hello!" />
<c:set var="publicVar" value="privateVar" />
${pageScope[pageScope.publicVar]}
oshilan
  • 23
  • 5

2 Answers2

0

The basics:

That's not JSTL but Expression Language. And you should only use a single ${} evaluator. The code would be:

${publicVar}

More info:


To your problem:

Expression Language doesn't allow that. You cannot have private attributes in any scope (page, request, session, application), so you can at most set the attribute twice with different names but the same value. But as you may note, this is useless.

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • i think op wants to resolve `Hello!` using `publicVar` -> `privateVar` – jmj Jun 19 '14 at 20:35
  • We can't use `publicVar`. We can use only `publicVar` which holds the name of `publicVar` as string. – oshilan Jun 19 '14 at 20:37
  • @oshilan you have a bad design. As noted here, it is futile. Why do you have to use such approach? It would be better if you add more details to the problem. – Luiggi Mendoza Jun 19 '14 at 20:39
0

I don't think you can directly do this in the same way that you can in PHP. Instead you could change the attribute to use the value of the privateVar instead of the name, like this:

String privateVar = "Hello!";
request.setAttribute("privateVar", privateVar);
request.setAttribute("publicVar", privateVar);

This gives you access to the value under both names, which I think is the closest you'd get. No need to even put the attribute privateVar in the request if you are ultimately going to use publicVar on the JSP.

Ultimately you may want to rethink the design here as it doesn't really work in Java.

nerdherd
  • 2,508
  • 2
  • 24
  • 40
  • Here's another question related to this: http://stackoverflow.com/questions/13298823/get-variable-by-name-from-a-string – nerdherd Jun 19 '14 at 20:38