Get key value inside map in Java

I'm not a Java developer, but I'm trying to figure out how to get the value from the map. I am using a basic (old) Struts app without any fancy stuff or JSTL afaik. I can get all the key / value pairs for output by converting the map to a string:

<% String myValue = pageContext.getSession().getAttribute("myMap").toString(); %>

      

However, when I try to access a specific key, it doesn't work:

<% String myValue = pageContext.getSession().getAttribute("myMap['myKey']").toString(); %>

      

+3


source to share


3 answers


<% String myValue = ((Map) pageContext.getSession().getAttribute("myMap")).get("myKey").toString(); %>
resp.
<% String myValue = ((Map) session.getAttribute("myMap")).get("myKey").toString(); %>
// because session is an implicit object in JSP

      

However, I would strongly discourage you from using such spaghetti code in JSPs. If you need to output the value of "myKey" you can use eg. <c:out>

with EL:



<c:out value="${session.myMap.myKey}" />
or
<c:out value="${session['myMap']['myKey']" />

      

+3


source


Assuming .getAttribute ("myMap") will return the Map object itself, you can use:
<% String val = pageContext.getSession().getAttribute("myMap").get(myKey).toString %>



0


source


Basically the session will return the type of the object. Please try the one below.

HashMap hmap11=(HashMap)pageContext.getSession().getAttribute("myMap");

      

it can work.

0


source







All Articles