Question

If I had code similar to the following, could I run it without any issues? I assume the Java will be run before the javascript, so the javascript won't have issues, but I haven't done this before:

<script type="text/javascript">
<% functThatOutputsJavascript() %>
</script>
Was it helpful?

Solution

This is very, very bad programming style, but yes, it is possible.

The code I am working on now has done some very similar stuff. I think you would actually want to do:

<script type="text/javascript">
    <%= functThatOutputsJavascript() %>
</script>

And actually, you can do even worse, using Java conditionals to modify the Javascript output:

<script type="text/javascript">
    while (i > 0) {
        <% if (serverVar)) { %>
            console.log("Server says yes!");
        <% } else { %>
            console.log("Server says no!");
        <% } %>
    }
</script>

This would then output this code if serverVar is true:

<script type="text/javascript">
    while (i > 0) {
            console.log("Server says yes!");
    }
</script>

or this code if it is false:

<script type="text/javascript">
    while (i > 0) {
            console.log("Server says no!");
    }
</script>

This is horrible coding style, and I hope you won't do it in practice! If you are wondering how to avoid writing code like this, check out this question: How to avoid Java code in JSP files?

A general suggestion would be to use JSP EL (JSP Expression Language) to set server side variables into your Javascript, and then write all of your logic in Javascript.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top