SpringMVC之使用 POJO 对象绑定请求参数值
Spring MVC 会按请求参数名和 POJO 属性名进行自动匹
配,自动为该对象填充属性值。支持级联属性。
如:dept.deptId、dept.address.tel 等
示例:
User实体类
package com.led.entities; /** * @author Alan * @date 2018/5/26 15:02 */ public class User { private String username; private String password; private int age; private String email; private Address address; 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } @Override public String toString() { return "User{" + "username='" + username + '\'' + ", password='" + password + '\'' + ", age=" + age + ", email='" + email + '\'' + ", address=" + address + '}'; } }
Address实体类
package com.led.entities; /** * @author Alan * @date 2018/5/26 15:04 */ 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 com.led.test; import com.led.entities.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; /** * @author Alan * @date 2018/5/25 22:03 */ @Controller @RequestMapping("/test") public class SpringMVCTest { private static final String SUCCESS = "success"; @RequestMapping("/testPojo") public String testPojo(User user){ System.out.println("User: " + user); return SUCCESS; } }
jsp页面:
<form action="test/testPojo" method="post"> username:<input type="text" name="username"/><br> password:<input type="password" name="password"/><br> email:<input type="text" name="email"/><br> age:<input type="text" name="age"/><br> province:<input type="text" name="address.province"/><br> city:<input type="text" name="address.city"/><br> <input type="submit" value="submit"> </form>
运行项目,输入信息:
点击提交按钮,控制台输出:
User: User{username='xiaoming', password='123456', age=11, email='1212@qq.com', address=Address{province='xizang', city='lasa'}}
本文来自博客园,作者:Javanumberone,转载请注明原文链接:https://www.cnblogs.com/stm32stm32/p/9092995.html
posted on 2018-05-26 15:16 Javanumberone 阅读(229) 评论(0) 编辑 收藏 举报