1

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??

Priya Prajapati
  • 304
  • 1
  • 4
  • 10
  • 2
    Why can't you just access the property from "currencyCodeMap" on the JSP side? It's really messy to mix JSP and JavaScript for a purpose like this; JSP is perfectly capable of extracting values from Map instances. – Pointy Jul 11 '13 at 12:56
  • I hope you are aware of this :http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files – Suresh Atta Jul 11 '13 at 12:58
  • as you are already using scriptlet, then why dont you iterate the map and fetch the required value in scriptlet itself. – Nitesh Mishra Jul 11 '13 at 13:01
  • @Pointy: Can you please provide some code how jsp is capable of extracting values from map.You can use my example – Priya Prajapati Jul 11 '13 at 13:07
  • @Nitesh Mishra : I had mentioned that I get key from a java script variable. – Priya Prajapati Jul 11 '13 at 13:08
  • Well it depends on exactly where the key is coming from, but map access in JSP is via the `[ ]` operator. Like, `currencyCodeMap[ key ]` – Pointy Jul 11 '13 at 13:09
  • as you are getting the key from form element, then you may submit the form with same page in the action, and then you can retrieve the key using `request` in scriptlet. Secondly, you may use AJAX and pass the key to another JSP and get back the value. As, merging JAVA and JavaScript is not a good practice. – Nitesh Mishra Jul 11 '13 at 13:15

1 Answers1

0

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}
dikkini
  • 1,184
  • 1
  • 23
  • 52