How to pass java variables from scriptlets to c:when expression in jstl?

我的梦境 提交于 2019-11-28 04:16:42

问题


what is a proper way to use variables from scriptlets in jstl? I don't know what is wrong in my code:

<%
boolean a = true;
boolean b = false;
%>

<c:choose>
    <c:when test="${a}">
        <c:set var="x" value="It's true"/>
    </c:when>
    <c:when test="${b}">
        <c:set var="x" value="It's false"/>
    </c:when>

</c:choose>

It looks like it doesn't go into the whole block.


回答1:


Variables in scriptlets cannot be seen in JSTL because Expression Language, the stuff between ${} used in JSTL, will look for attributes in page, request, session or application. You have to at least store the variable from scriptlet in one of these scopes, then use it.

This is an example:

<%
    boolean a = true;
    request.setAttribute("a", a);
%>

<c:if test="${a}">
    <c:out value="a was found and it's true." />
</c:if>

More info:

  • Expression Language StackOverflow wiki
  • JSTL StackOverflow wiki

As a recommendation, stop using scriptlets. Move the business logic in your JSP to controller and the view logic into EL, JSTL and other tags like <display>. More info: How to avoid Java code in JSP files?




回答2:


The default scope of JSP is page. if you want to use the variable of scriplet to JSTL use following code.

<%
    boolean a = true;
    boolean b = false;
    pageContext.setAttribute("a", a);
    pageContext.setAttribute("b", b);
%>

Then it will be usable in JSTL.



来源:https://stackoverflow.com/questions/25893913/how-to-pass-java-variables-from-scriptlets-to-cwhen-expression-in-jstl

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