我在 index.jsp 中有Spring表单:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<body>
<form:form action="save" name="employeeDTO" method="POST">
<label for="name">Name</label><input id="name" type="text" required><br>
<label for="surname">Surname</label><input id="surname" type="text" required><br>
<label for="email">E-mail</label><input id="email" type="email" required><br>
<label for="salary">Salary</label><input id="salary" type="number" required><br>
<input type="submit" value="Save">
</form:form>
</body>
</html>
在 WorkController.java 中,我尝试映射表单提交(目前,它对数据不执行任何操作):
@Controller
public class WorkController {
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@RequestParam EmployeeDTO employeeDTO){
return "saved";
}
}
但是我得到了HTTP 400状态:
Required EmployeeDTO parameter 'employeeDTO' is not present
和描述:The request sent by the client was syntactically incorrect.
有 EmployeeDTO.java :
public class EmployeeDTO implements Serializable, DTO {
private Long id;
private String name;
private String surname;
private String email;
private Double salary;
public EmployeeDTO(){}
public EmployeeDTO(Long id, String name, String surname, String email, Double salary){
this.id = id;
this.name = name;
this.surname = surname;
this.email = email;
this.salary = salary;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
@Override
public Serializable toEntity() {
return new Employee(getId(), getName(), getSurname(), getEmail(), getSalary());
}
}
如果我从
@RequestParam EmployeeDTO employeeDTO
方法签名中删除save
-它起作用,它将重定向到saved.jsp
文件。之前,我使用@RequestParam String name, @RequestParam String surname etc
从HTML表单中捕获数据。有什么解决方案可以将Spring表单中的数据“捕获”为DTO对象?如果因残酷决定帮助我,我将感到非常高兴-预先感谢您。 最佳答案
您可以尝试使用@ModelAttribute
(访问ModelAttribute question in SO以获得清晰的了解)
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@ModelAttribute("employeeDTO") EmployeeDTO employeeDTO){
return "saved";
}
我用了这个
in spring mvc 3.1