How to set int value into variable using JSTL tags?

18.6k Views Asked by At

Whenever doing <c:set var="emp"><cq:text property="empid" /></c:set> is always giving me string. But var suppose to return 'int'. Is there any any to get 'int' instead of 'string'

Thanks

2

There are 2 best solutions below

0
On

You are using the <cq:text> tag which is per se a string. Try the following:

<c:set var="emp" value="${properties['empid']}"/>

If the property is a number in CRX this should return a number as well. Else you would need to use a scriptlet to read the property type safe:

<%
int empid = properties.get("empid", Integer.class);
%>
0
On

You can use the <fmt:parseNumber> tag, which is already available in CQ5 (the <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> library is referenced by global.jsp) and which is a good thing to do to avoid scriptlets. This example is detailed at http://www.tutorialspoint.com/jsp/jstl_format_parsenumber_tag.htm:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<html>
<head>
  <title>JSTL fmt:parseNumber Tag</title>
</head>
<body>
<h3>Number Parsing:</h3>
<c:set var="balance" value="1250003.350" />

<fmt:parseNumber var="i" type="number" value="${balance}" />
<p>Parsed Number (1) : <c:out value="${i}" /></p>
<fmt:parseNumber var="i" integerOnly="true" 
                       type="number" value="${balance}" />
<p>Parsed Number (2) : <c:out value="${i}" /></p>

</body>
</html>

This would produce following result:

Number Parsing:

Parsed Number (1) : 1250003.35

Parsed Number (2) : 1250003