java – Spring 4 – HTTP Status 400,不存在必需参数

我在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状态:必需的EmployeeDTO参数’employeeDTO’不存在描述:客户端发送的请求在语法上是不正确的.

有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 – 它可以工作,它会重定向到saved.jsp文件.之前,我使用@RequestParam String name,@ RequestParam String surname等来从HTML表单中捕获数据.有没有解决方案从Spring表单“捕获”数据作为DTO对象?如果abyody决定帮助我,我会很高兴 – 谢谢你提前.

解决方法:

您可以尝试使用@ModelAttribute(访问ModelAttribute question in SO以清楚地了解它)

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@ModelAttribute("employeeDTO") EmployeeDTO employeeDTO){
    return "saved";
}

我在春季mvc 3.1中使用过它

上一篇:Bump Mapping综述


下一篇:HDR高动态范围光照渲染