我在弹簧输入表单中传递对象(CarType)有问题。
我的车型:
@Entity
@Table(name="CAR")
public class Car implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "CAR_ID", unique=true, nullable=false)
private long id;
@NotEmpty
@Column(name = "REG_NO", nullable=false)
private String regNo;
@NotEmpty
@Column(name = "YEAR", nullable=false, length = 4)
private String year;
@Column(name = "AVAILABLE", nullable=false)
private boolean available = true;
@Column(name = "START_DATE")
private String startDate;
@Column(name = "RETURN_DATE")
private String returnDate;
@OneToOne
@JoinColumn(name="CAR_TYPE_ID")
private CarType carType;
//getters and setters
车型型号:
@Entity
@Table(name = "CAR_TYPE")
public class CarType {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "CAR_TYPE_ID", unique=true, nullable=false)
private int id;
@NotEmpty
@Column(name = "MARK", nullable=false)
private String mark;
@NotEmpty
@Column(name = "MODEL", nullable=false)
private String model;
//getters and setters
控制器:
@RequestMapping(value = { "/rent-car-{regNo}" }, method = RequestMethod.GET)
public String rentCar(@PathVariable String regNo, ModelMap model) {
Car car = carService.findCarByRegNo(regNo);
model.addAttribute("car", car);
return "rentcar";
}
@RequestMapping(value = { "/rent-car-{regNo}" }, method = RequestMethod.POST)
public String saveRentCar(@Valid Car car, BindingResult result, ModelMap model) {
carService.updateCar(car);
model.addAttribute("success", "Car " + car.getRegNo() + " rented successfully");
return "registrationsuccess";
}
JSP文件
<form:form method="POST" modelAttribute="car" class="form-horizontal">
<form:input type="hidden" path="id" id="id"/>
<form:input type="hidden" path="year" id="year"/>
<form:input type="hidden" path="regNo" id="regNo"/>
<form:input type="hidden" path="available" id="available"/>
<form:input type="hidden" path="carType" id="carType"/>
<form:input type="text" path="startDate" id="startDate"/>
<form:input type="text" path="returnDate" id="returnDate"/>
我的代码有问题
<form:input type="hidden" path="carType" id="carType"/>
如何将对象CarType传递给Car表单?我总是有同样的错误:列&#39; CAR_TYPE_ID&#39;不能为空。看起来我将空CarType转移到Car。我不知道为什么? 有人可以帮帮我吗?在registercar.jsp中,我使用了转换器(将regNo转换为类CarType)及其工作原理。
答案 0 :(得分:2)
您需要知道Car
对象如何从来自客户端的http请求绑定到Controller处理程序方法中。 Spring MVC映射请求参数以构造Car
对象。因此CarType
是一个关联的对象。你需要为Spring MVC提供一个最小的线索,为你构建它。
<form:form method="POST" action="/rent-car${regNo}" modelAttribute="car">
......
<form:input type="hidden" path="carType.id"/>
<form:input type="hidden" path="carType.model"/>
<form:input type="hidden" path="carType.mark"/>
<input type="submit" value="Submit"/>
</form:form>
你会在这篇文章Spring MVC - Binding Request Parameters and Path Variables to Java Backing Objects
中找到一个补充例子