Skip to content Skip to sidebar Skip to footer

How To Loop Through Java List Object In JavaScript?

Controller List permissionList = new ArrayList(); //fill permissionList with list of object ayyays (objetct[0] = permission id, object[1] = permission) model.add

Solution 1:

Java code runs on the server. JavaScript runs on the client. They are very different languages and do not interoperate out of the box. When you need to pass data from Java to JavaScript, the easiest is to serialize it to JSON using Jackson for example.

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper om = new ObjectMapper();
model.addAttribute("permissionList", om.writeValueAsString(permissionList));

and in the JSP:

var allpermissionList = ${permissionList};

Note that not all Java object are serializable to JSON so the objects in your list should be simple Java types (String, Number...) or POJOs.


Solution 2:

I got resolved .. thanks all.

Controller

List<Object[]> permissionList = new ArrayList();
// load values
List<Map<String, String>> listAll = new ArrayList<>();
   if (permissionList != null && permissionList.size() > 0) {
       for (Object[] objects : allPermissions) {
           Map map = new HashMap();
           map.put("id",objects[0]);
           map.put("permName", objects[1]);
           listAll.add(map);
        }
    }

ObjectMapper mapper = new ObjectMapper();
String permissionList = mapper.writeValueAsString(listAll);
model.addAttribute("permissionList", permissionList);

Jsp

 var allpermissionList = eval(${permissionList});
  $.each(allpermissionList, function (index, permission) {
     var id = permission.id;
     var name = permission.name;

 });

Post a Comment for "How To Loop Through Java List Object In JavaScript?"