27

I have to access the JSTL variable which is calculated inside the iterator.
Excerpt of code:

<c:forEach var="resultBean" items="${resultList}" varStatus="status">
   card: ${resultBean.cardNum} 
</c:forEach>

i would like to access ${resultBean.cardNum} in the scriptlet code. what i am doing right now is:

<c:forEach var="resultBean" items="${resultList}" varStatus="status">
   card: ${resultBean.cardNum} 
   <c:set var="currentCardNum">${resultBean.cardNum}</c:set>
   <%out.write( StringUtils.mask( (String)pageContext.getAttribute("currentCardNum") ) );%>
</c:forEach>

I want to skip 3rd line where i am setting the variable in pageContext. Is it possible to achieve the same result without setting it? Or is there other way round which i can use?

Rakesh Juyal
  • 35,919
  • 68
  • 173
  • 214

2 Answers2

19

You can try the following:

<%
  ResultBean resultBean = (ResultBean) pageContext.getAttribute("resultBean");
  out.write( StringUtils.mask( resultBean.getCardNum() ) );
%>

BTW - you can add another method to resultBean - getMaskedCardNum(), and then just put in the page ${resultBean.maskedCardNum} which is more readable.

Ajinkya
  • 22,324
  • 33
  • 110
  • 161
David Rabinowitz
  • 29,904
  • 14
  • 93
  • 125
7

I'd advise creating a custom JSTL function (check this for example), so that you can omit the scriptlet. So instead of the ugly

<%out.write( StringUtils.mask( (String)pageContext.getAttribute("currentCardNum") ) );%>

you will have something like:

<c:out value="${fnPrefix:maskString(currentCardNum)}" />
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140