OntZ
OntZ

Reputation: 263

jstl - how do i pass an expression language variable to a javascript alert?

I'm trying to make an admin page connected to a servlet, where I can insert some elements into a database. It's a demo of a concert ticket booking website and I use a form to input data, and the servlet to validate it.

If the servlet finds invalid data in one or more of the form's fields, it returns a custom message as a formatted string named mismatchOut - one invalidity message per line, e.g.:

Concert date must be in yyyy-mm-dd format!
start time must be in hh:mm:ss format!

I pass this in my jsp as:

<c:set var="invalidConcertInputMessage" value="${mismatchOut}" scope="page" />

What I want to do is pass this message to an alert, which will show the message to the admin user.

I've tried:

<c:if test="${not empty invalidConcertInputMessage}">
    <script>
        alert("${invalidConcertInputMessage}");
    </script>
</c:if>

,

<c:if test="${not empty invalidConcertInputMessage}">
    <script>
        alert(${invalidConcertInputMessage});
    </script>
</c:if>

,

<c:if test="${not empty invalidConcertInputMessage}">
    <script>
        alert(<c:out value="${invalidConcertInputMessage}");
    </script>
</c:if>

,

<c:if test="${not empty invalidConcertInputMessage}">
    <script>
        alert("<c:out value="${invalidConcertInputMessage}" />");
    </script>
</c:if>

and:

<c:if test="${not empty invalidConcertInputMessage}">
    <script>
        alert('<c:out value="${invalidConcertInputMessage}" />');
    </script>
</c:if>

and nothing seems to work. I'm probably missing the sintax here, as I'm a total newbie when it comes tu UI.

This works and prints out an alert saying "some text":

<c:if test="${not empty invalidConcertInputMessage}">
    <script>
        alert("some text");
    </script>
</c:if>

Please tell me how I can pass my custom message to the alert. Or is this even possible?

Upvotes: 2

Views: 3664

Answers (1)

OntZ
OntZ

Reputation: 263

It seems the problem was that I was posting newline characters to my custom message string as \n, but java parsed them as its own newlines, instead of just sending \n to java script, which resulted in some form of invalid string that it wouldn't parse.

I fixed the problem by replacing \n with\n` in the custom string sent by the servlet.

And for anyone else in this predicament, this is the syntax that I got it working with:

<c:if test="${not empty invalidConcertInputMessage}">
    <script>
        var message = "${invalidConcertInputMessage}";
        alert(message);
    </script>
</c:if>

Upvotes: 4

Related Questions