简体   繁体   中英

How to get value from a java map using key in a jsp, but key is a javascript value

I have a jsp page , In this page I get a hash map from request attribute and I want to extract value for a specific key . The key is availble on jsp . how can I extarct value from map using this key?

I solved this problem by converting java map to java script associative array and then I could fetch value from that array. I would like to share the code :

<%
Map<String,String> currencyCodeMap = (Map<String,String>)application.getAttribute("currPrecisionCodeMap"); 
%>

<script language="javascript">


        var map = new Array();
        <%
        for (Map.Entry<String, String> entry : currencyCodeMap.entrySet()) {%>
                map['<%=entry.getKey()%>'] = '<%=entry.getValue()%>';
        <%}
        %>

var currencyCode = document.AccForm.currencyname.options[document.AccForm.currencyname.selectedIndex].text;

   alert(map[currencyCode ]);// gives value

</script>

above code is working fine but Can Someone provide better solution??

If i understand your question right, you have init your hashmap in JSP using , than using JSTL u can iterate it.

<jsp:useBean id="hm" type="java.util.Hashtable<java.lang.Long, java.util.ArrayList<java.lang.String>>" scope="request"/>

<c:forEach items="${hm[key]}" var="item">
    <c:out value="${item.value}" />
</c:forEach>

Also, you can do next:

pageContext.setAttribute("key", your_key);

And than using it in JSTL:

${your_key}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM