Tiny
Tiny

Reputation: 27909

Comparing numeric values in JSTL/EL

I'm comparing numeric values in the following way in JSTL.

<c:set var="testValue" value="10"/>

<c:choose>
    <c:when test="${testValue==10}">
        <c:out value="Test is successful."/>
    </c:when>
    <c:otherwise>
        <c:out value="Test is unsuccessful."/>
    </c:otherwise>
</c:choose>

The condition is evaluated to true and it displays - "Test is successful."

If the value of the variable testValue is not numeric like,

<c:set var="testValue" value="xxx"/>

then the test fails with the following exception.

javax.el.ELException: Cannot convert xxx of type class java.lang.String to class java.lang.Long

Because the string is not parsable to Long. The comparison is done lexicographically.

This can be avoided by using EL like the following.

<c:set var="testValue" value="${xxx}"/>

In this case, the text in the <c:otherwise> section would be displayed.


I'm using such a construct while retrieving data from a database like,

<c:forEach var="row" items="${list}" varStatus="loop">
    <c:choose>
        <c:when test="${param.edId==row.id || row.id==param.id}">
            // Do something.
        </c:when>

        <c:otherwise>
            // Do something.
        </c:otherwise>
    </c:choose>
</c:foreach>

In the above code, the value of row.id is guaranteed to be Long that corresponds to the Number datatype in the Oracle database.

The values of param.edId and/or param.id are however not guaranteed to be numeric and can be changed by malicious users. In that case, an unexpected error as above may occur.


Do I really need to set two extra variables for this like,

<c:set var="paramId" value="${param.id}"/>
<c:set var="paramEdId" value="${param.edId}"/>

and use them in the loop above or is there a concise way to avoid that parse exception (in case, the values are not parsable)?

Upvotes: 1

Views: 7100

Answers (1)

JB Nizet
JB Nizet

Reputation: 692181

First of all, I wouldn't care at all if my JSP generated an exception due to a malicious user changing a parameter value.

But This wouldn't happen if you used the MVC pattern, and started to fill a command/form object with the parameters sent by the browser. That way, you would have typed variables instead of strings, and you would compare those typed variables with the typed values coming from the database.

Upvotes: 1

Related Questions