torikraju torikraju - 1 month ago 8
Java Question

Spring MVC form handling form multiple pojos

i'm new in Spring mvc i want some help to understanding some form handling.Suppose i have two pojo like..

public class Loginfo{
private String username;
private String password;

setters and getter...
}


another class is like..

pubic class PersonalInfo{
private String name;
private String age;
private Loginfo loginfo;
setters and getter...
}


and lastly i have a form having fields-> username, password, name , age

How do i handle this form. i mean what should be the controller code..

Answer

You would need a JSON converter in your application. You can use Jackson for this purpose. You will need the Jackson core,databind and annotation jars/dependencies for this. Make sure all three jars/dependencies are of same version.

Add below to dispatcher-servlet:

<beans:bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <beans:property name="messageConverters">
            <beans:list>
                <beans:ref bean="jsonMessageConverter" />
            </beans:list>
        </beans:property>
    </beans:bean>

    <!-- Configure bean to convert JSON to POJO and vice versa -->
    <beans:bean id="jsonMessageConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </beans:bean>

The above code will directly convert objects to JSON and vice versa whenever an http request comes in to the controller.

The code in controller would look like:

@RequestMapping(value = "/serviceName", method = RequestMethod.POST, headers = "Accept=application/json")
    public @ResponseBody void service(@RequestBody PersonalInfo personalInfo){
}

Make sure the name of the var you post is personalInfo.

Comments