单个jsp表单spring mvc

时间:2017-07-02 04:08:28

标签: java spring jsp spring-mvc

我创建了一个单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");
}`

1 个答案:

答案 0 :(得分:1)

我用这种方式意识到了你的问题: 您需要在控制器中使用一个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);
            }

}

我希望这就是你要找的东西。