[英]I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error
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?
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. 相比之下,JSTL完全可以使用
page
, request
或session
范围内的范围属性。 You need to rework your scriptlet to fish test
out as an attribute: 您需要重新编写脚本以将其作为属性进行
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. 更好的是,根本不要使用scriptlet:它们会使婴儿耶稣哭泣。
@skaffman nailed it down. @skaffman钉牢了它。 They live each in its own context.
他们各自生活在自己的环境中。 However, I wouldn't consider using scriptlets as the solution.
不过,我不会考虑使用小脚本作为解决方案。 You'd like to avoid them.
您想避免它们。 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: 如果您只想连接EL中的字符串,而您发现
+
运算符对EL中的字符串失败(这是正确的),则只需执行以下操作:
<c:out value="abc${test}" />
Or if abc
is to obtained from another scoped variable named ${resp}
, then do: 或者,如果要从另一个名为
${resp}
作用域变量获取abc
,请执行以下操作:
<c:out value="${resp}${test}" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.