Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

But it seems not working.

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

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

like image 691
pythoniosIV Avatar asked Dec 23 '12 00:12

pythoniosIV


1 Answers

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.

like image 142
BalusC Avatar answered Oct 21 '22 17:10

BalusC