0

I am using Hashmap<String, String> from the controller in the jsp. I need to parse the Hashmap and get the value passing the Key. I am trying to get the value by passing the key using the get method of hashmap, but it is not working.

var key = "keyString";
var valueStr = <%=hashMap.get(key)%>;

The above code is giving the error, key cannot be resolved to a variable. But when I am hardcoding the key value in the hashmap I am able to get the value.

var valueStr = <%=hashMap.get("keyString")%>;
Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135
user903676
  • 319
  • 1
  • 4
  • 10

2 Answers2

0

You're trying to reference key in the context of the JSP scriptlet, which is compiled on the server side. Not only is it in a different context entirely, but your JavaScript is handled on the client side, after the JSP scriptlet (compiled by the server) is already resolved.

In short, key isn't a variable until after the scriptlet is already resolved.

Zircon
  • 4,677
  • 15
  • 32
  • thanks for your answer Zircon. it will be helpfull if you can let me know the best possible approach to parse the Java hashmap in Javascript. TIA. – user903676 Apr 22 '16 at 13:16
  • Since you're using Strings, this answer may work for you - http://stackoverflow.com/a/8877719/4793951 – Zircon Apr 22 '16 at 13:22
0

JSP is compiled at server side and Simple HTML is returned to client back. You are expecting the client side variable (In browser's JVM) should be used for JSP Scriplet evaluation. Then you should pass it along with request to server.

Chaitu
  • 61
  • 5