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

2019-01-09 18:26发布

问题:

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.