2

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>
EGr
  • 2,072
  • 10
  • 41
  • 61

1 Answers1

0

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.

Community
  • 1
  • 1
JBCP
  • 13,109
  • 9
  • 73
  • 111
  • Thanks. I haven't even started writing anything yet (which is why I asked), so I'll look into avoiding this style. I might use it to temporarily get something working. – EGr Feb 18 '14 at 02:31
  • The use-cases where you would need this should be very, very slim. It would be MUCH better to use the JSP Expression language to get the results you want. – JBCP Feb 18 '14 at 16:28