java 如何将java变量从scriptlets传递给jstl中的c:when表达式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25893913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:53:55  来源:igfitidea点击:

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

javajspjstlscriptlet

提问by Peters_

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

在jstl中使用来自scriptlet的变量的正确方法是什么?我不知道我的代码有什么问题:

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

看起来它没有进入整个块。

回答by Luiggi Mendoza

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.

在 JSTL 中无法看到 scriptlet 中的变量,因为在 JSTL 中使用的表达式语言${}将在页面、请求、会话或应用程序中查找属性。您必须至少将 scriptlet 中的变量存储在这些范围之一中,然后使用它。

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?

作为建议,停止使用 scriptlet。将 JSP 中的业务逻辑移至控制器,将视图逻辑移至 EL、JSTL 和其他标签,如<display>. 更多信息:如何避免 JSP 文件中的 Java 代码?

回答by Yogendra Joshi

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

JSP 的默认范围是页面。如果你想将 scriplet 的变量用于 JSTL,请使用以下代码。

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

Then it will be usable in JSTL.

然后它将在 JSTL 中可用。