我创建了一个单一的jsp表单,希望将数据发送到两个表。这意味着我创建了两个模型类,因此表单应引用这两个模型类。我尝试过,但是失败了。如何从一个jsp页面获取两个modelAttribute并将其分配给一个控制器。提前致谢。

`@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表格

<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>


控制者

@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");
}`

最佳答案

我以这种方式实现了您的问题:
您需要控制器中的一个api返回两种类型的数据。

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> {
}


并将您的实体更改为

public class Survey1 implements Serializable,IActionResult<Survey1>

 public class Survey2 implements Serializable,IActionResult<Survey2>


并在您的控制器中

@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);
            }

}


我希望这是您要寻找的。

10-07 18:54
查看更多