Java 我可以将变量从 JSP 脚本传递到 JSTL,但不能从 JSTL 传递到 JSP 脚本而不会出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3570191/
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
I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error
提问by Cornish
The following code causes an error:
以下代码导致错误:
<c:set var="test" value="test1"/>
<%
String resp = "abc";
resp = resp + test;
pageContext.setAttribute("resp", resp);
%>
<c:out value="${resp}"/>
The error says
错误说
"error a line 4: unknown symbol 'test'".
How do I pass test
from the JSTL code to the JSP scriptlet?
如何test
从 JSTL 代码传递到 JSP scriptlet?
采纳答案by skaffman
Scripts are raw java embedded in the page code, and if you declare variables in your scripts, then they become local variables embedded in the page.
脚本是嵌入在页面代码中的原始 java,如果您在脚本中声明变量,那么它们将成为嵌入在页面中的局部变量。
In contrast, JSTL works entirely with scoped attributes, either at page
, request
or session
scope. You need to rework your scriptlet to fish test
out as an attribute:
相比之下,JSTL工作完全与范围属性,无论是在page
,request
或session
范围。您需要重新编写脚本以test
将其作为属性进行处理:
<c:set var="test" value="test1"/>
<%
String resp = "abc";
String test = pageContext.getAttribute("test");
resp = resp + test;
pageContext.setAttribute("resp", resp);
%>
<c:out value="${resp}"/>
If you look at the docs for <c:set>
, you'll see you can specify scope
as page
, request
or session
, and it defaults to page
.
如果您查看 的文档<c:set>
,您会发现您可以指定scope
为 page
、request
或session
,并且默认为page
。
Better yet, don't use scriptlets at all: they make the baby jesus cry.
更好的是,根本不要使用scriptlets:它们会让婴儿耶稣哭泣。
回答by BalusC
@skaffman nailed it down. They live each in its own context. However, I wouldn't consider using scriptlets as thesolution. You'd like to avoidthem. If all you want is to concatenate strings in EL and you discovered that the +
operator fails for strings in EL (which is correct), then just do:
@skaffman 把它搞定了。他们每个人都生活在自己的环境中。不过,我不会考虑使用小脚本作为该解决方案。你想避免它们。如果您只想连接 EL 中的字符串,并且您发现+
运算符对 EL 中的字符串失败(这是正确的),那么只需执行以下操作:
<c:out value="abc${test}" />
Or if abc
is to obtained from another scoped variable named ${resp}
, then do:
或者,如果abc
要从另一个名为 的范围变量中获取${resp}
,则执行以下操作:
<c:out value="${resp}${test}" />