1 Question: How to get a list of objects in jQuery from s:hidden tag in Struts 2

Question created on Sunday February 26, 2017

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:



2 answer                              3                         

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"%>
    var list = [];
    <c:forEach items="${objects}" var="o">

Or same stuff with old-school scriplets..

<% for(int i = 0; i < objects.size(); i++) { %>
<% } %>
Friday February 24, 2017

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());
Sunday February 26, 2017
source posted here