我可以将变量从 JSP 脚本传递到 JSTL,但不能从 JSTL 传递到 JSP 脚本而不会出错 [英] I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

查看:21
本文介绍了我可以将变量从 JSP 脚本传递到 JSTL,但不能从 JSTL 传递到 JSP 脚本而不会出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码导致错误:

 <c:set var="test" value="test1"/>
 <%
   String resp = "abc";
   resp = resp + test;
   pageContext.setAttribute("resp", resp);
 %>
 <c:out value="${resp}"/>

错误说

"error a line 4: unknown symbol 'test'".

如何将 test 从 JSTL 代码传递到 JSP scriptlet?

How do I pass test from the JSTL code to the JSP scriptlet?

推荐答案

脚本是嵌入在页面代码中的原始 java,如果你在脚本中声明变量,那么它们就会成为嵌入页面的局部变量.

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.

相比之下,JSTL 完全使用范围属性,无论是在 pagerequest 还是 session 范围内.您需要重新编写 scriptlet 以将 test 作为属性取出:

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:

<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}"/>

如果您查看 <c:set> 的文档,您会发现可以将 scope 指定为 page, requestsession,默认为page.

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.

更好的是,根本不要使用 scriptlet:它们会让婴儿耶稣哭泣.

Better yet, don't use scriptlets at all: they make the baby jesus cry.

这篇关于我可以将变量从 JSP 脚本传递到 JSTL,但不能从 JSTL 传递到 JSP 脚本而不会出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆