1
votes

I created a single jsp form which wants to send data to two table. It means I created two model class, so the form should refer those two model class. I tried, but failed. How to get two modelAttribute from one jsp page and assign to one controller. Thanks in advance.

`@Entity
@Table(name = "survey")
public class Survey {
    // all anotations and getters and setters are omitted
    private int surveyId;
    private String surveyName;

}

@Entity
@Table(name = "preferred")
public class Survey {
    // all anotations and getters and setters are omitted
    private int preferredId;
    private String preferredClass;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="surveyId")
    private Survey survey;
}

jsp form

<spring:url value="/survey/save" var="saveURL"></spring:url>
<form:form action="${saveURL}" method="POST" modelAttribute="surveyForm">

    //Survey model class
    <form:hidden path="surveyId" /> 
    <form:input path="surveyName" />

    //preferredClass model class
    <form:input path="preferredClass">      

    <button type="submit" >Submit</button>  

</form:form>

Controller

@RequestMapping(value = "/save", method = RequestMethod.POST)
//here I need to get ModelAttribuete of Survey and preferredClass
public ModelAndView saveSurvey( @ModelAttribute("surveyForm") Survey survey ,.........// how to get attributes of preferredClass  ) {

    surveyService.saveOrUpdate(survey); 
    return new ModelAndView("redirect:/survey/list");
}`
1
Either create two forms on front end, or, create a composite object and use it on your form. - Moshe Arad
Im new to spring, could you please give me a example? - varman
Why two same Survey objects?? - Moshe Arad
No I need preferredClass object - varman

1 Answers

1
votes

I realized your question in this way: you need one api in your controller to return two type of data.

IActionResult.java

public interface IActionResult<T> {
}

ActionResultBase.java

public abstract class ActionResultBase<T> implements 

    IActionResult<T>,Serializable {
    }

ActionResult.java

public class ActionResult<T> extends ActionResultBase<T> {
}

and chang your entity to

public class Survey1 implements Serializable,IActionResult<Survey1> 

 public class Survey2 implements Serializable,IActionResult<Survey2> 

and in your controller

@RequestMapping(value = "/save", method = RequestMethod.POST)
 //here I need to get ModelAttribuete of Survey and preferredClass
 public ResponseEntity<IActionResult> saveSurvey( @ModelAttribute("surveyForm") Survey survey)
    {
       if(your desired condition 1){
           //do your Business
           return new ResponseEntity<IActionResult>(survay1, HttpStatus.OK(any things you like);
           }

        if(your desired condition 2){                
           //do your Business    
           return new ResponseEntity<IActionResult>(survay2, tpStatus.OK(any things you like);
            }

}

I hope this is what you are looking for.