使用 POJO 对象绑定请求参数
- 概述
Spring MVC 会按请求参数名和 POJO 属性名进行自动匹配,自动为该对象填充属性值并且支持级联属性。这一特性在日常开发过程中使用频率比较高,开发效率也高,本文主要对 POJO 对象绑定请求参数做一个简单是示例。
- 定义 POJO 对象
package rex.springmvc.domain; public class User { private String userNm; private String pwd; private Integer age; private Address address; public String getUserNm() { return userNm; } public void setUserNm(String userNm) { this.userNm = userNm; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
package rex.springmvc.domain; 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; } }
- Handler
package rex.springmvc.handlers; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import net.sf.json.JSONObject; import rex.springmvc.domain.User; @RequestMapping(value="/pojoTestHandler") @Controller public class PojoTestHandler { private static final Logger logger = Logger.getLogger(HelloWordHandler.class); private static final String SUCCESS = "success"; @RequestMapping(value="/testPojo", method=RequestMethod.POST) public String testPojo(User user){ JSONObject json = JSONObject.fromObject(user); logger.debug(json.toString()); return SUCCESS; } }
- 页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>POJO Test</title> </head> <body> <form action="pojoTestHandler/testPojo" method="post"> userNm: <input type="text" name="userNm"><br> pwd: <input type="password" name="pwd"><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> </body> </html>
- 运行结果