JavaScript variable in EL expression

丶灬走出姿态 提交于 2020-01-11 12:55:23

问题


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...


回答1:


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.



来源:https://stackoverflow.com/questions/13786167/javascript-variable-in-el-expression

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