torikraju torikraju - 9 months ago 50
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 Source

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:property name="messageConverters">
                <beans:ref bean="jsonMessageConverter" />

    <!-- Configure bean to convert JSON to POJO and vice versa -->
    <beans:bean id="jsonMessageConverter"

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.