SpringMVC学习(四)之使用POJO作为参数

当表单有众多项时,像之前一个一个传递参数比较麻烦,可以使用POJO直接将表单数据存储到实体类中

步骤一:创建POJO

package entity;

public class Address {
    private String province;
    private String city;
    public String getProvince() {
        return province;
    }
    public void setProvince(String province) {
        this.province = province;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    @Override
    public String toString() {
        return "Address [province=" + province + ", city=" + city + "]";
    }
}
package entity;

public class User {
    private String name;
    private int age;
    private Address address;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + ", address=" + address
                + "]";
    }

}

步骤二: 创建控制器

/**
     *Spring MVC 会按请求参数名和 POJO 属性名进行自动匹配,
     *自动为该对象填充属性值。支持级联属性
     */
    @RequestMapping(value="/testPojo")
    private String testPojo(User user) {
        System.out.println("testPojo "+user);
        return SUCCESS;
    }

步骤三:请求表单

"springmvc/testPojo" method="post"> 用户名:type="text" name="name">
年龄:type="text" name="age">
省份:type="text" name="address.province">
城市:type="text" name="address.city">
type="submit" value="submit">

你可能感兴趣的:(SpringMVC)