0

I have code as below, I want to do all in Java code to create categoryListMap object, then convert to categoryList, how can I do?

    ...
    var categoryList = [];

<%
    List<Object> modelMaster = psiSearchForm.getModelMaster();
    String parentKey = "";
    String categoryKey = "";
    String text = "";

    for (int i = 0; i < modelMaster.size(); i++) {
        Map option = (Map) modelMaster.get(i);

        parentKey = (String)option.get(ConstantContainer.MODALITY);
        categoryKey = (String)option.get(ConstantContainer.CATEGORY);
        text = categoryKey + ": " + (String)option.get(ConstantContainer.CATEGORY_NAME);
%>
        categoryList.push({
            parent: "<%=parentKey%>",
            key: "<%=parentKey%><%=categoryKey%>",
            text: "<%=text%>"
        }); 
<%
    }
%>
6
  • JSP expressions are not chuck norris it cant call array.push of javascript from Java. Only chuck norris has that power. Commented Jun 14, 2017 at 5:21
  • I mean After created List Map in java, then use for loop in javascript to push to categoryList, may I make sense? Commented Jun 14, 2017 at 5:23
  • you can create a JSON object and assign that to categoryList Commented Jun 14, 2017 at 5:23
  • can you show me a sample Commented Jun 14, 2017 at 5:24
  • Yes your code is sufficient, I can understand what you are trying to do. But that is impossible. Java cant call javascript in a template. You can instead create a json object and assign that to categoryList Commented Jun 14, 2017 at 5:25

1 Answer 1

0

You are trying to call JavaScript function in JSP, this is not possible. You can instead create the array in JSP and set the final value in javascript.

<body>
<%

    JSONArray arr = new JSONArray();
    for(int i =0; i < 5; i++) {
        JSONObject object = new JSONObject();

        object.put("name", "santa"+i);
        object.put("mail", "santa"+i+"@email.com");

        arr.add(object);
    }

%>
    <script>
        var obj = <%= arr %>;

        console.log("JS obj", obj);
    </script>
</body> 

The library I am using is json-simple-1.1.1.jar.

page import

<%@page import="org.json.simple.JSONObject,org.json.simple.JSONArray"%>
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.