1

What's the best way to send a list of objects from a Struts 2 action to JavaScript?

I'm trying to send data this way but it just doesn't work

Action >>> JSP : <s:hidden>  >>> Javascript

<s:hidden id="listObj" value="%{objects}" />

This line get me object names array as a string:

$('#listObj').val()

Thanks

2 Answers 2

1

Convert a list of objects to JSON like this

String objectsJson = new Gson().toJson(objects);

You should use getters to access a variable in jsp.

Now, you need to parse this text via javascript. You can use JSON.parse('${objectsJson}') in JSP to get a javascript object or if the object is stored in hidden field

var objects = JSON.parse($('#listObj').val());
1

You have to iterate over the list of objects to populate your js array, using JSTL:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<script>
    var list = [];
    <c:forEach items="${objects}" var="o">
        list.push("${o}")
    </c:forEach>
</script>

Or same stuff with old-school scriplets..

<% for(int i = 0; i < objects.size(); i++) { %>
    ...
<% } %>
1
  • +1 for the iteration, -1 for the old-school scriptlets. Change scriptlets with OGNL way for a positive net :) Feb 24, 2017 at 9:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.