unable to get list value in spring 3.0 mvc

my regForm.jsp is:

    <form:form action="save.html">
    form:label path="name">Name *</form:label>
    <form:input path="name" />
    <form:label path="hobbies">Hobbies *<br />use (ctrl) botton to multiple select </form:label>
    <form:select path="hobbies" id="hobbies" multiple="true"
                                items="${hobList}" itemValue="id" itemLabel="hobbyName">
    </form:select>
    <input type="submit" value="Submit" onclick="addFormValidate()" />
    </form>

My Beans

public class User {
    private int id;     
    priavte List<Hobby> hobbies;
    //setter getter
}

public class Hobby {
    private int id;
    private String hobbyName;
    //setter getter
}

myController.java

@RequestMapping(value = "/save.html", method = RequestMethod.POST)
    public ModelAndView addEmployee(
            @ModelAttribute("user") User user BindingResult result) {           
        System.out.println("name"+user.getName() );



    System.out.println(employee.getHobbies()); // getting null  
    //   usrDao.saveUser(user);
return new ModelAndView("redirect:add.html", model);
}

How could i get the value for List from my form so that i could get the value? **What is wrong in my code? **

Answer

Here is the code—-

package com.programsji.converter;

    import org.springframework.core.convert.converter.Converter;

    import com.programsji.bo.Hobby;

    public class StringToHobbyConverter implements Converter<String, Hobby> {

        @Override
        public Hobby convert(String str) {
            // I Am Using Fix Hobbies Here, You Can Add Your Own Method to Get
            // Hobbies By ID
            Hobby hobby = null;
            if (str.equals("1")) {
                hobby = new Hobby(1, "First Hobby");
            } else if (str.equals("2")) {
                hobby = new Hobby(2, "Second Hobby");
            }
            return hobby;
        }

    }

To Register…

<annotation-driven conversion-service="conversionService" />
    <beans:bean id="conversionService"
        class="org.springframework.context.support.ConversionServiceFactoryBean">
        <beans:property name="converters">
            <beans:list>
                <beans:bean class="com.programsji.converter.StringToHobbyConverter" />
            </beans:list>
        </beans:property>
    </beans:bean>

It is working on my pc. if you need, I can send you source code. About conversionService registration, you can view this example:

http://www.programsji.com/spring/converter

Leave a Reply

Your email address will not be published. Required fields are marked *