直接在scriptlet中使用EL ${XY} <% XY %>

编程入门 行业动态 更新时间:2024-10-14 12:21:05
本文介绍了直接在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;

本文发布于:2023-11-14 20:12:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1588411.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:XY   EL   scriptlet   gt   lt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!