0

I'm trying to modularize my JSTL code. A particular code needs to be called in many places inside a JSP so I've separated it out in a separate INC file. In my JSP, I include the file using <%@ include file="snippet.inc" %>. The snippet needs to work on some variables in page context, determined by the caller.

I'm storing the NAME of the relevant variable in a variable called __var which will be used by the snippet. The expectation is that the snippet will read and modify the actual variable in pageScope whose name is passed via __var.

The JSP file:

<c:set var="name1" value="Admin"></c:set>
<c:set var="name2" value="Moderator"></c:set>

<c:set var="__var" value="name1"></c:set>
<%@ include file="snippet.inc" %>
${name1}


<c:set var="__var" value="name2"></c:set>
<%@ include file="snippet.inc" %>
${name2}

The INC file:

<c:set var="__value" value="${pageScope[__var]}"></c:set>
<c:set var="${pageScope[__var]}"> Hello ${__value} </c:set>

The first line works fine and I can read the value of the variable name. The second line does not work and complains that I can't use expressions as variable names.

How do I go about this issue?

AweSIM
  • 1,651
  • 4
  • 18
  • 37

1 Answers1

1

It's things like these that make you realize what a wonderful thing StackOverflow is! Found and modified a solution from https://stackoverflow.com/a/8750411/1101040 to achieve my cause.

<c:set var="__value" value="${pageScope[__var]}"></c:set>
<c:set target="${pageScope}" property="${__var}"> Hello ${__value} </c:set>

All set! :)

Community
  • 1
  • 1
AweSIM
  • 1,651
  • 4
  • 18
  • 37