本文介绍了在Scriptlet中访问JSTL/EL变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码会导致错误:

<c:set var="test" value="test1"/>
<%
    String resp = "abc";
    resp = resp + ${test};  //in this line I got an  Exception.
    out.println(resp);
%>

为什么我不能在小脚本中使用表达语言"$ {test}"?

Why can't I use the expression language "${test}" in the scriptlet?

推荐答案

JSTL 变量实际上是属性,默认情况下在页面上下文级别范围内.
因此,如果您需要在scriptlet中访问JSTL变量值,则可以通过调用 getAttribute() 方法在适当范围内的对象(通常为 pageContext 并请求).

JSTL variables are actually attributes, and by default are scoped at the page context level.
As a result, if you need to access a JSTL variable value in a scriptlet, you can do so by calling the getAttribute() method on the appropriately scoped object (usually pageContext and request).

resp = resp + (String)pageContext.getAttribute("test");

完整代码

 <c:set var="test" value="test1"/>
 <%
    String resp = "abc";
    resp = resp + (String)pageContext.getAttribute("test");   //No exception.
    out.println(resp);
  %>

JSP脚本用于包含任何代码对页面中使用的脚本语言有效的片段.脚本的语法如下:

A JSP scriptlet is used to contain any code fragment that is valid for the scripting language used in a page. The syntax for a scriptlet is as follows:

<%
   scripting-language-statements
%>

将脚本语言设置为Java时,脚本小程序将转换为Java编程语言语句片段,并将其插入JSP页面Servlet的服务方法中.

When the scripting language is set to Java, a scriptlet is transformed into a Java programming language statement fragment and is inserted into the service method of the JSP page’s servlet.

在scriptlet中,您可以编写Java代码,而在非Java代码中可以编写${test}.

In scriptlets you can write Java code and ${test} in not Java code.

不相关

这篇关于在Scriptlet中访问JSTL/EL变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-21 13:40