通过pojo获取请求参数

114 阅读1分钟

可以在控制器方法的形参位置设置一个实体类类型的形参,此时若浏览器传输的请求参数的参数名和实体类中的属性名一致,那么请求参数就会为此属性赋值。

<form th:action="@{/testpojo}" method="post">
    id:<input type="text" name="id"><br>
    用户名:<input type="text" name="username"><br>
    密码:<input type="text" name="password"><br>
    年龄:<input type="text" name="age"><br>
    性别:<input type="text" name="sex"><br>
    邮箱:<input type="text" name="email"><br>
      <input type="submit" value="提交">
</form>
public class User {
    private Integer id;
    private String username;
    private String password;
    private  Integer age;
    private String sex ;
    private String email;

    public User() {
    }

    public User(Integer id, String username, String password, Integer age, String sex, String email) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.age = age;
        this.sex = sex;
        this.email = email;
    }


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + ''' +
                ", password='" + password + ''' +
                ", age=" + age +
                ", sex='" + sex + ''' +
                ", email='" + email + ''' +
                '}';
    }
}
@RequestMapping("/testpojo")
public String testPojo(User user){
    System.out.println(user);
    return "success";
}