JavaScript variable in EL expression

In my servlet I'm sending many values back to JSP page by for cycle like this:

protected void doGet(HttpServletRequest request, HttpServletResponse response){
    for (int i = 0; i < veryBigNumber; i++){  
        if (something){  
            request.setAttribute("value" + i, "true");  
        else{  
            request.setAttribute("value" + i, "false");  
    }  
}

And in JSP I would like to read them in the same way with JavaScript and EL:

<script>  
    for (var i=0; i < veryBigNumber; i++){  
        if ("${value + (i)}" == "true"){  
            doSomething;  
        } else{  
            doSomethingElse;   
    }  
}  
</sctipt>

The problem is I don't know how to make the variable i a part of EL expression. Is it possible? And if yes, how?
Thanks...

Answers:

Answer

You're making a conceptual mistake here. Java/JSP/EL runs on webserver and produces HTML/CSS/JS which in turn runs in webbrowser (rightclick page in webbrowser and do View Source to see it yourself). Yet you're expecting that EL and JS runs in sync in the webbrowser. This is not true.

You basically need to perform the iteration and EL evaluation using JSP instead and write it accordingly so that it prints the proper JS code you want.

<script>
    <c:forEach begin="0" end="${veryBigNumber - 1}" var="i">
        <c:set var="value" value="value${i}" />
        <c:choose>
            <c:when test="${requestScope[value]}">
                doSomething;
            </c:when>
            <c:otherwise>
                doSomethingElse;   
            </c:otherwise>
        </c:choose>
    </c:forEach>
</script>

Note that this particular construct is clumsy and a code smell. The concrete functional requirement is not exactly clear, so it's not possible to propose the more elegant solution for whatever you're trying to achieve.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.