springController:
- @Controller
- @RequestMapping("/user")
- public UserController extends BaseController{
- @RequestMapping("/addUser")
- public void testBinderOuput(@ModelAttribute User user, HttpServletRequest request, HttpServletResponse response){
- System.out.println(user);
- }
- }
Use对象:
- public Class User{
- private String name;
- private int sex;
- private String address;
- private int id;
- public int getSex() {
- return sex;
- }
- public void setSex(int sex) {
- this.sex = sex;
- }
- public String getAddress() {
- return address;
- }
- public void setAddress(String address) {
- this.address = address;
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
请求路径:
localhost/user/addUser?user.name="test"
那么在后台接受到的参数中,user对象的name属性是null。如果路径换为localhost/user/addUser?name="test",则user对象的name属性是test。
这里必须用name="test"而不是user.name="test",因为默认情况下springMVC是不支持user.name这种传参方式的。
如果有个对象manager中也有name这个相同的属性,那么可以采用user.name,manager.name来传输参数。但是这个需要在controller中添加一个前缀绑定:
添加绑定前缀后的controller类如下:
- @Controller
- @RequestMapping("/user")
- public UserController extends BaseController{
- @InitBinder("manager")
- public void initBinder1(WebDataBinder binder) {
- binder.setFieldDefaultPrefix("manager.");
- }
- @InitBinder("user")
- public void initBinder2(WebDataBinder binder) {
- binder.setFieldDefaultPrefix("user.");
- }
- @RequestMapping("/addUser")
- public void testBinderOuput(@ModelAttribute User user, HttpServletRequest request, HttpServletResponse response){
- System.out.println(user.getName);
- }
- @RequestMapping("/addManager")
- public void testBinderOuput(@ModelAttribute Manager manager, HttpServletRequest request, HttpServletResponse response){
- System.out.println(manager.getName);
- }
- }
这样在使用连接localhost/user/addUser?user.name="test",去请求时,后台拿到的name的参数就不为null了。
有个专门讨论这个问题的主题:http://www.iteye.com/topic/1124433?page=2可以参考下