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:
- Server runs any JSP and produces a new page. After this step, any JSP things are complete.
- Server sends that generated page to the client
- Client (browser) sees the page, maybe runs some Javascript (if present)
Your desired behavior is:
- Javascript code runs first, checks the
if
statement condition, then proceeds with the body of the if
statement only when "condition" was true.
- JSP code inside the Javascript
if
block runs
The actual behavior is:
- JSP code runs first, no matter what your intended code logic is. All JSP throughout the entire page will run first, always.
- The output of the JSP code is mixed with the rest of the static HTML+Javascript in the apge.
- The browser gets involved for the first time, seeing the newly-created page: JSP output + static HTML and Javascript.
- Browser runs any Javascript in the page.
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.