5

I have a controller class in Spring MVC, where i am returning a HaspMap as Model attribute -

@ModelAttribute("regPrefix")
public Map<String, String> getRegPrefixesOfDepartmentforGroup(final Model model, final HttpServletRequest request) {
    final Map<String, String> regPrefixOfDept = new HashMap<String, String>();
    regPrefixOfDept.put(regKey, regPrefix);
    return regPrefixOfDept;
}

Now in the corresponding JSP page, i am trying to access the Hashmap and store the key/value pairs of the Hasmap in a variable using JavaScript. I am trying like below but its not right. Can anyone suggest how to do that

<script>
        $("#deptIdSelection").change(function()
        {
            var obj = document.getElementById("deptIdSelection");
            var textItem = obj.options[obj.selectedIndex].text;
            alert(textItem);
            var mapObj = "${regPrefix}";
            for(var key in mapObj)
                alert(key +" ->"+ mapObj[key]);

         }
        );
</script>

1 Answer 1

4

Try to access map values like this:

${regPrefix.key} 

If you want to iterate through the map keys, it is not so easy: JSTL is executed on the server side and is rendered to a plain text - no JavaScript objects are created. The following line var mapObj = "${regPrefix}"; will be rendered to a string representation of HashMap, not to a JavaScript object.

To convert your map to a JavaScript object I suggest you to use one of the following methods:

1) Convert your map to JSON and pass it as a String. So when it is rendered to a JavaScript code, it will look like a regular JS object: var mapObj = {"key": "value", ...};. You can use Gson or any other JSON library to achieve this:

final Map<String, String> regPrefixOfDept = new HashMap<String, String>();
regPrefixOfDept.put(regKey, new Gson().toJson(regPrefixOfDept));

And then var mapObj = ${regPrefix}; (note that you need no quotes around because you want mapObj to be a JS object, not a string)

2) Iterate through your map using <c:forEach> to generate a JS object:

var mapObj = {
    <c:forEach items="${regPrefix}" var="item" varStatus="loop">
      ${item.key}: '${item.value}' ${not loop.last ? ',' : ''}
    </c:forEach>
};

In both cases you should be able to then call

for(var key in mapObj)
   alert(key +" ->"+ mapObj[key]);
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.