我创建了一个单个jsp表单,它想要将数据发送到两个表。这意味着我创建了两个模型类,因此表单应该引用这两个模型类。我尝试过,但失败了。如何从一个jsp页面获取两个 modelAttribute 并分配给一个 Controller 。提前致谢。
`@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>
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");
}`
最佳答案
我是这样理解你的问题的: 您的 Controller 中需要一个 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>
在你的 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);
}
}
我希望这就是您正在寻找的内容。
关于java - 来自单个 jsp 表单 spring mvc 的多模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44867368/