本文介绍了直接在scriptlet中使用EL ${XY} <% XY %>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,每次打开 JSP 时我都必须分配一个变量.我在 JSP 和 EL ${} 中使用 scriptlets <% %> 尝试了它,它返回变量.

In my project I've to assign a variable every time the JSP is being opened.I tried it with scriptlets <% %> in JSP and EL ${} which gives the variable back.

但它似乎不起作用.

 <% String korrekteAntwort=${frage.korrekteAntwort};%>
 <%session.setAttribute("korrekteAntwort", korrekteAntwort);%>

korrekteAntwort=${} 后出现错误,是不是可以在scriptlet 中直接从EL 赋值?

There is an error after korrekteAntwort=${}, Isn't it possible to assign directly an variable from EL in a scriptlet?

推荐答案

您正在混合 scriptlets 和 EL,并期望它们同步"运行.那是行不通的.一种是老派的 JSP 编写方式另一种是编写 JSP 的现代方式.您应该使用其中一个,而不是两者都使用.

You're mixing scriptlets and EL and expecting that they run "in sync". That just won't work. The one is an oldschool way of writing JSPs and the other is a modern way of writing JSPs. You should use the one or the other, not both.

回到具体问题,在幕后,EL 通过 PageContext#findAttribute().所以只需在 scriptlets 中做完全相同的事情.

Coming back to the concrete question, under the hoods, EL resolves variables by PageContext#findAttribute(). So just do exactly the same in scriptlets.

Frage frage = (Frage) pageContext.findAttribute("frage");
session.setAttribute("korrekteAntwort", frage.getKorrekteAntwort());

但是,如上所述,这是使用 JSP 的老派方式,不一定是 您想到的功能需求,但没有提及.现代 JSP 方式将使用 JSTL :

However, as said, this is an oldschool way of using JSPs and not necessarily the "best" way for the functional requirement which you've had in mind, but didn't tell anything about. The modern JSP way would be using JSTL <c:set>:

<c:set var="korrekteAntwort" value="${frage.korrekteAntwort}" scope="session" />

这将在会话范围内作为 ${korrekteAntwort} 从该行开始可用,这正是 scriptlet 行所做的.

This will be available in session scope as ${korrekteAntwort} from that line on, which is exactly what that line of scriptlet does.

这篇关于直接在scriptlet中使用EL ${XY} &lt;% XY %&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 14:10