Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
861 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...