Use EL ${XY} directly in scriptlet <% XY %>

独自空忆成欢 提交于 2019-12-17 10:03:33

问题


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

But it seems not working.

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

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


回答1:


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.

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());

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

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



来源:https://stackoverflow.com/questions/14007689/use-el-xy-directly-in-scriptlet-xy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!