Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i use JSTL variable in scriptlet?

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?

like image 431
Rakesh Juyal Avatar asked Dec 28 '09 12:12

Rakesh Juyal


People also ask

How use Javascript variable in JSP scriptlet tag?

Your javascript values are client-side, your scriptlet is running server-side. So if you want to use your javascript variables in a scriptlet, you will need to submit them. To achieve this, either store them in input fields and submit a form, or perform an ajax request.

Can we use JSTL in Javascript?

The JSTL fn:escapeXml() function is useless when you're interpolating a JSP variable into a part of the page that will be interpreted as Javascript source by the browser. You can either use a JSON library to encode your strings, or you can write your own EL function to do it.

Can we use JSTL tags in HTML?

No. It is not possible to have JSTL in HTML page.


2 Answers

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.

like image 189
David Rabinowitz Avatar answered Oct 11 '22 15:10

David Rabinowitz


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)}" />
like image 7
Bozho Avatar answered Oct 11 '22 13:10

Bozho