I hope everyone is doing well!
I was wondering if there was a way to write JSP code inside a Javascript if-statement?
For instance, the testVoid() method from the funStuff.java class changes a certain String in the class, and then retK() returns that String.
However, the JSP code runs irrespective of the condition in the if-statement. I saw another post that stated using JSTL could resolve this, but I am not sure how to write the intended code segment using JSTL.
Any help would be appreciated! Thanks!
<script> if (false) { <% funStuff.testVoid(); %> } console.log('<%= funStuff.retK() %>'); </script>
I was wondering if there was a way to write JSP code inside a Javascript if-statement?
No, this isn't possible.
At a high-level, once the request lands at the server:
Your desired behavior is:
if
statement condition, then proceeds with the body of the if
statement only when "condition" was true. if
block runs The actual behavior is:
Your example starts like this as JSP:
<script>
if (false) {
<%
funStuff.testVoid();
%>
}
console.log('<%= funStuff.retK() %>');
</script>
The server will evaluate the JSP <%... %>
bits, so for example, assume that:
funStuff.testVoid()
returns "xyz" funStuff.retK()
returns "K" then the server will produce this:
<script>
if (false) {
xyz
}
console.log('K');
</script>
The browser will receive the output as above, having no knowledge that "xyz" or "K" were generated on the fly vs. being pre-written into the page, or that JSP scriptlets were involved in any way.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.