是否可能,如果是的话,如何使用Java Spring Form创建一个对象并将其放入其他对象中?因为我需要创建"引擎"反对并将其放入" Car"宾语。这是我的代码"引擎"和" Car":
public class Engine {
private float volume;
private int id;
public float getVolume() {
return volume;
}
public void setVolume(float volume) {
this.volume = volume;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
public class Car {
private int id;
private Engine engine;
private String model;
public Engine getEngine() {
return engine;
}
public void setEngine(Engine engine) {
this.engine = engine;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
我在使用本教程:http://www.codejava.net/frameworks/spring/spring-mvc-form-handling-tutorial-and-example 学习如何创建表单。
我创建了这个表单:
<form:form action="register" method="post" commandName="carForm">
<table border="0">
<tr>
<td>Model:</td>
<td><form:input path="model" /></td>
</tr>
<tr>
<td>Volume:</td>
<td><form:password path="volume" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Register" /></td>
</tr>
</table>
</form:form>
因此,使用&#34; volume&#34;创建Engine对象的任何方法都是如此。从形式和后来输入这个&#34;引擎&#34;反对&#34; Car&#34;宾语?因为我在Google中找到的每个表单示例都只创建一个对象。
答案 0 :(得分:0)
根据评论,我理解的是你想要一个Car对象中的Engine对象,这样你就可以获得Engine对象的细节。
您有两种选择:
1)像你一样在Car对象中声明一个Engine对象:
public class Car {
private Engine engine;
// getters and setters
}
2)使用强大的继承功能。
public class Car extends Engine {
private int id;
private String model;
// extending Engine object gives you direct access to Engine objects variables
}
在为Car创建表单时使用继承模型,而不使用&#34;引擎调用Engine变量。&#34;。
答案 1 :(得分:0)
我找到了问题的解决方案,这是我的表格:
<form action="/Lab05/submitAdmissionForm.html" method="post">
<p>
Pojemnosc : <input type="number" step="0.1" name="volume" />
</p>
<p>
Model : <input type="text" name="model" />
</p>
<input type="submit" value="Submit" />
</form>
这是我的控制器:
@RequestMapping(value = "/submitAdmissionForm.html", method = RequestMethod.POST)
public ModelAndView submitAdmissionForm(@RequestParam("volume") float volume,
@RequestParam("model") String model) {
ModelAndView modelView = new ModelAndView("AdmissionSuccess");
Engine engine = new Engine();
engine.setVolume(volume);
Car car = new Car();
car.setEngine(engine);
car.setModel(model);
modelView.addObject("msg", "Details submited by you: Volume: " + car.engine.getVolume() + " Model: " + car.getModel());
return modelView;
}