简体   繁体   中英

How put Map's Keys in <select> on JSP

I have next problem. In JSP I wrote next

<select name='subject'>
    <c:forEach items="${subjects.keySet()}" var="subjectID">                  
        <option>${subjects.get(subjectID).getName()}</option>                    
    </c:forEach>
</select> 

And I get there values from Map. But I don't know how I can get key for choosen subject on servlet

I tried to do this

String subjectID = request.getParameter("subjectID");

Thanks

I try to do it But

<select name='subject'>                
                <c:forEach var="subject" items="${subjects}">
                    <option id="${subject.key}" value="${subject.value.getName()}">
                        ${subject.value.getName()}
                    </option> 
                </c:forEach>
            </select>

Error on jsp: Bad value for attribute id

I need show name subject on jsp. But on servlet get ID subject

<select name='subject'>    
    <c:forEach items="${yourMap}" var="yourEntry">
        <option>${yourEntry.key}</option>
    </c:forEach>
</select>

Or, if you want to access properties on the key.

<select name='subject'>    
    <c:forEach items="${yourMap}" var="yourEntry">
        <option>${yourEntry.key.theProperty}</option>
    </c:forEach>
</select>

You can access the associated value with .value in place of .key .

Let say, "subjects" is your HashMap

<select name='subject'>  
   <c:forEach var="subject" items="${subjects}">
       <option id="${subject.key}" value="${subject.value.getName()}">${subject.value.getName()}</option>   
   </c:forEach>
</select>

If you want to pass Key as value then change to value="${subject.key}" .So, On submitting form. You r key will be passed.

<select name='subject'>
    <c:forEach items="${subjects}" var="subject" >                  
        <option value="${subject.key}">
            ${subject.value.getName()}
        </option>                    
    </c:forEach>
</select>

And on servlet I did next

Integer subjectIdByName = Integer.valueOf(request.getParameter("subject"));

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