1

So, I am trying to pass a Set into a .jsp page using Spring and JSP EL, and then assign the members of the set to a Javascript array to use later in client-side scripts.

For example, if I have the Java Set exampleSet: { "A", "B", "C"}

I pass it to the client side as part of a spring ModelandView object.

In the client-side JSP, I can use EL to output the set as ${model.exampleSet} , which gets parsed into [A, B, C] by JSP.

What I want to do is assign the contents of exampleSet to an array of javascript strings, so you get something like

var exampleSet = ["A", "B", "C"]

I can't find a direct way to do this. The other obvious approach to this is to loop through the Set, but as I can't work out the size of the Set in javascript, I don't think I can do this either.

4
  • 1
    You could use any one of a number of JSP tags that are designed to iterate over a collection, such as the JSTL <c:forEach> tag. Commented Aug 22, 2012 at 15:40
  • Anthony, thanks, I think that should work. Still wondering if there's a more elegant way to do it though. Commented Aug 22, 2012 at 15:45
  • Why is using JSTL to render your javascript not elegant? As mentioned by @mplungjan if you want to return just the JavaScript array as part of the response, you can write a JSON string to the response outputstream instead. But if you want a JavaScript array IN the HTML you probably already have, this is the way. Commented Aug 22, 2012 at 15:48
  • I was hoping to keep JSTL Tags out of my Javascript scripts, basically. Commented Aug 22, 2012 at 15:57

1 Answer 1

4

JavaScript executes on the browser. The JSP is rendered on the server. You're missing the lifetimes of the execution environments here.

What you would do is

<script>
var exampleSet = [
  <c:forEach var="item" items="${theSetVariable}" varStatus="loop">
    "${item}"
    <c:if test="${!loop.last}">,</c:if>
  </c:forEach>
]
<script>

So, you're looping through the Set in the JSP, to create the HTML/JavaScript, that creates code to represent the Javascript array when rendered on the browser.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.