使用POJO对象绑定请求参数值(6)

2020-03-18 14:11:56 浏览数 (2)

SpringMVC 会按请求参数名和POJO属性名进行自动匹配,自动为该对象填充属性值。支持级联属性

代码语言:javascript复制
public class User {

    private String username;
    private String password;

    private String email;
    private int age;
    private Address address;

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

    public String getUsername() {
        return username;
    }

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

    public String getPassword() {
        return password;
    }

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

    public String getEmail() {
        return email;
    }

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

    public int getAge() {
        return age;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public Address getAddress() {
        return address;
    }

    @Override
    public String toString() {
        return "User{"  
                "username='"   username   '''  
                ", password='"   password   '''  
                ", email='"   email   '''  
                ", age="   age  
                ", address="   address  
                '}';
    }
}
代码语言:javascript复制
public class Address {

    private String province;
    private String city;

    public void setProvince(String province) {
        this.province = province;
    }

    public String getProvince() {
        return province;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCity() {
        return city;
    }

    @Override
    public String toString() {
        return "Address{"  
                "province='"   province   '''  
                ", city='"   city   '''  
                '}';
    }
}
代码语言:javascript复制
@Controller
@RequestMapping("/springmvc")
public class TestController {


    /**
     * SpringMVC 会按请求参数名和POJO属性名进行自动匹配
     * @param user
     * @return
     */
    @RequestMapping("/testPojo")
    public String testPojo(User user){
        System.out.println("testPojo : "   user);
        return "success";
    }
}
代码语言:javascript复制
<form action="/springmvc/testPojo" method="post">
    username:<input type="text" name="username">
    password:<input type="password" name="password">
    email:<input type="text" name="email">
    age:<input type="text" name="age">
    city:<input type="text" name="address.city">
    province:<input type="text" name="address.province">
    <input type="submit" name="Submit">
</form>

0 人点赞