简体   繁体   中英

JSTL c:set not working as expected

I have a JSTL loop where I'm trying to check to see if a given variable is empty or not with a dynamic variable name. When I use c:set with page scope, the variable is not accessible to the if statement. However, when I set it using <% pageCotnext.setAttribute(...); %> <% pageCotnext.setAttribute(...); %> , the variable is available.

<%
pageContext.setAttribute("alphaParA", "test");
pageContext.setAttribute("alphaParF", "test");
int i = 0;
%>
<ul class="alphadex_links">
    <c:forEach var="i" begin="0" end="25" step="1" varStatus="status">
        <c:set var="currentLetter" scope="page">&#${i+65}</c:set>
        <c:set var="currentPar" scope="page">alphaPar${currentLetter}</c:set>
        <% pageContext.setAttribute("currentPar", "alphaPar" + (char)('A' + i++)); %>
        <li>
            <c:choose>
                <c:when test="${not empty pageScope[currentPar]}">

The test is always fails when I remove the pageContext.setAttribute block, however it succeeds for A and F as it should when the block is in. I'm very confused and can't find help anywhere.

It fails because HTML doesn't run at the moment JSTL runs. You're effectively passing a Java String &#65 to it instead of the desired character A which would be represented as such based on the HTML entity &#65; when the HTML is retrieved and parsed by the webbrowser after Java/JSP/JSTL has done its job. Please note that your HTML entity is missing the closing semicolon, but this isn't the cause of your concrete problem.

As to the concrete functional requirement, sorry, you're out of luck with EL. It doesn't support char . Your best bet is to deal with strings like this:

<c:forEach items="${fn:split('A,B,C,D,E,F,G,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z', ',')}" var="currentLetter">
    <c:set var="currentPar" value="alphaPar${currentLetter}" />
    ${pageScope[currentPar]}
</c:forEach>

If necessary, just autogenerate the letters as String[] in Java end and set it as application attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM