简体   繁体   中英

Spring: Accessing List of Model Attributes in JSP Dropdown

From my controller, I am sending a list of objects to my jsp view. I am using spring form:select tag to make the dropdown which works, but it shows the weird object reference in memory. How can I get it to just show the name attributes of the objects that I pass in.

    <form:form commandName="game">
       <form:select path="name" items="${listOfGames}"></form:select>
    </form:form>

This code gives me a drop down of game objects, but I want the dropdown to show the name attribute

If you just use the items attribute as above, spring will try to "stringify" your list/array elements, ie call toString() in each of them and since you have not overridden it, the one defined in Object. An exception to this is whenever you pass a Map<String, String> where the keys are used for the value attribute and the values for display.

You have to use the form:options tag properly to explicitly declare which property is used for key and which one for display

<form:select path="game">
    <form:options items="${listOfGames}" itemValue="id" itemLabel="name"/>
</form:select>

assuming you want to bind the id property

My guess is that the problem is because you are not using the options tag.

<form:form commandName="game">
   <form:select path="name"> 
       <form:options items="${listOfGames}" />
   </form:select>
</form:form>

TRY THIS::::

<form:form method="post" commandName="game">
<form:select path="name">
<form:option label="Setect A Game"/>
<form:options items="${listOfGames}"/>
</form:select> 
</form:form>

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