0
我有一個這樣的實體類Employee。它哈瓦對象部(一個其他實體)Spring:無法提交表單編輯一個實體有外鍵
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@NotNull
@NotEmpty
@Valid
private String name;
@DateTimeFormat(pattern="dd/MM/yyyy")
@Valid
private Date date;
private String cmt;
private String address;
private String position;
private Boolean matrimony = true;
@ManyToOne
@Valid
private Department department;
}
控制器,創建控制器顯示一個編輯頁面,並添加控制器解決增加請求:
@RequestMapping(value = "/employee/add", method = RequestMethod.POST)
public String add(@Validated @ModelAttribute(value = "employee") Employee employee) {
employeeRepository.save(employee);
return "redirect:./list";
}
@RequestMapping(value = "/employee/create")
public ModelAndView create(ModelMap mm) {
mm.addAttribute("action", "add");
mm.addAttribute("employee", new Employee());
mm.addAttribute("dao", new DepartmentDAO(departmentRepository));
return new ModelAndView("../jsp/employee/edit.jsp");
}
視圖,它是表格輸入員工的數據和提交添加方法。
<form:form method="POST" action="${website_url}" commandName="employee">
<form:hidden path="id"></form:hidden>
<div class="form-group">
Name:
<form:input path="name" class="form-control"></form:input>
</div>
<div class="form-group">
Date of birth:
<form:input path="date" class="form-control"></form:input>
</div>
<div class="form-group">
ID card number:
<form:input path="cmt" class="form-control"></form:input>
</div>
<div class="form-group">
Address:
<form:input path="address" class="form-control"></form:input>
</div>
<div class="form-group">
Department:
<form:select path="department.id" class="form-control">
<% for(Department department : departmentDAO.departmentRepository.findAll()){%>
<form:option value="<%= department.getId() %>">
<%= department.getName() %>
</form:option>
<% } %>
</form:select>
</div>
<div class="form-group">
Position:
<form:select path="position" class="form-control">
<form:option value="Director">Director</form:option>
<form:option value="Department Leader">Department Leader</form:option>
<form:option value="Employee">Employee</form:option>
</form:select>
</div>
<div class="form-group form-inline">
Matrimony:
<form:checkbox path="matrimony" class="form-control"></form:checkbox>
</div>
<input type="submit" value="save" class="btn btn-primary form-control" />
</form:form>
我運行彈簧,它正確加載編輯頁面。但由於外鍵部門,我提交了表格,因此我收到了400個錯誤的請求。
嘗試將您的表單動作屬性更改爲'action =「$ {pageContext.request.contextPath}/employee/create」' –
是的,我的代碼中包含它!如果沒有,我會得到404找不到,但400請求不好。 –
我不認爲我理解。你的問題解決了嗎? –