Search code examples
springspring-mvcspring-4spring-form

SpringMVC - Displaying objects in form:options


Hi I am completely from a mobile background, so Spring is new to me, I have currently I have a form called as BusinessForm here are the contents

public class BusinessForm 
{
 private String selectedBusinessId; //getters and setters included
 private List businessNameList; //getters and setters included - list of Business class Objects
  private List businessIdList; //getters and setters included  - lisy of Business class Objects
//Business class defined below 
}

Here is my Controller

@Controller 
public class HomeController{
    @RequestMapping(value = "/showHome", method = RequestMethod.GET)
    @ExceptionHandler({CutsomException.class})
    public ModelAndView showHome()
    {
         //Init BusinessForm class, its defined above...
         //set values of businessNameList...
         //set values of businessIdList...
         BusinessForm businessForm = new BusinessForm();
         businessForm.setBusinessNameList(....);
         businessForm.setBusinessIdList(....);
         return ModelAndView("MyView","businessForm", businessForm)
    }
}

Here is my view (I will show only the form to avoid showing everyhting else)

MyView.jsp

<form:form action="blah" method="post" modelAttribute="businessForm">
<form:select path="selectedBusinessId">
<form:option value="">Select ID</form:option>
<form:options items="${businessForm.businessIdList}" item/>
</form:select>              
</form:form>

So right now my businessIdList seen is above code for form:options items attribute is a list of "Business" objects and the Business objects have private variables businessName and businessId with getter and setters

public class Business
{
  private String businessId; //with getters and setter 
  private String businessName; //with getters and setters 
}

so in the form above once I open the drop down its actually showing me a list, but that String is nothing but the toString() function of Business class. So my drop down items are looking like com.xxx.Business@c291000. Wihtout overriding toString() of Business class, how do I make my form to display the actual businessId on the drop down of the form list. The reason is I want to get another form:select and display another list of businessName. Please help. Thanks.


Solution

  • You need to change your

    <form:select path="selectedBusinessId">
        <form:option value="">Select ID</form:option>
        <form:options items="${businessForm.businessIdList}" item/>
    </form:select>
    

    to

    <form:select path="selectedBusinessId">
        <form:option value="">Select ID</form:option>
        <form:options items="${businessForm.businessIdList}" itemValue="businessId" itemLabel="businessName" />
    </form:select>