JSP/JSTL: '2 > 10' Evaluates to true

孤街醉人 提交于 2019-12-13 18:09:28

问题


I have a very simple custom JSP tag that I am using to generate pagination links. It goes roughly like:

<span id="${id}" class="paginationLinks ${cssClass}">
    <c:if test="${currentPage gt 1}">
        <!-- Links to previous page(s) -->
    </c:if>
    <span class="paginationCurrentPage">
        Page ${currentPage} 
        [DEBUG:  current=${currentPage}, 
                 total=${totalPages}, 
                 show=${currentPage lt totalPages} 
                 inverse=${currentPage gt totalPages}]
    </span>
    <c:if test="${currentPage lt totalPages}">
         <!-- Links to next page(s) -->
    </c:if>
</span>

The problem is that the links to go to the next page are not showing up after the first page (currentPage = 1). The links to go to previous pages are working correctly across every page. I'm also getting some truly bizarre output from my debug block:

[DEBUG: current=1, total=10, show=true inverse=false]    //first page, correct
[DEBUG: current=2, total=10, show=false inverse=true]    //second page; 2 > 10 == true?  wtf???
[DEBUG: current=9, total=10, show=false inverse=true]    //ninth page, still incorrect
[DEBUG: current=10, total=10, show=false inverse=false]  //tenth page, correct

Both currentPage and totalPages are request attributes of type long and are passed to the tag via declared tag attributes. So what have I done wrong to produce such insane output as 2 > 10 == true?

Update

It works correctly if I replace totalPages with a literal 10 in the comparison, but that really does not solve the problem.


回答1:


Solution found. I needed to explicitly declare the type on my tag attributes, like:

<%@ attribute name="currentPage" required="true" type="java.lang.Long" %>
<%@ attribute name="totalPages" required="true" type="java.lang.Long" %>

I suspect that without the declared type both attributes were being interpreted as Strings, and the tag was doing a lexicographical comparison between the string values of the numbers. I assume a literal value of 10 worked because the JSP interpreter recognized it as a proper numerical type and then automatically converted the other argument in the comparison to match.

So long story short, always declare a type on your tag attributes. Otherwise very confusing things can happen.



来源:https://stackoverflow.com/questions/6688636/jsp-jstl-2-10-evaluates-to-true

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!