SpringMVC参数绑定高级

本文介绍如何在Web应用中实现不同类型的参数绑定,包括简单类型、数组、POJO类、List集合和Map映射等,帮助开发者更好地理解并运用这些技术。

想要彻底掌握复杂类型的参数绑定,需要掌握简将简单类型绑定到pojo类中

例如:

pojo类

User{
	private String username;
	private String password;
	private String address;
}
请求

<!--需要将请求的名称与pojo类的属性名一致-->
<form action="" method="post">
	用户名:<input type="text" name="username" />
	密码:<input type="text" name="password"/>
	地址:<input type="text" name="address" />
	<input type="submit" value="提交" />
</form>
Controller

@RequestMapping("test")
//请求参数需要与User类的属性名对应
public String test(User u) throws Exception{
	System.out.println(u.getUserName());
}


1、绑定数组

//请求参数:http://localhost:8080/...?item_id=xxx&item_id=yyy
@RequestMapping("/deleteItem.action")
	public String test_array(Integer[] item_id) throws Exception{
		for(int id:item_id){
			System.out.println(id);
		}
		return "/WEB-INF/jsp/itemsList.jsp";
	}

2、绑定pojo类

pojo类及pojo包装类

public class User{	//pojo类
	private String userName;
}
public class Teacher{	//pojo包装类
	private User user;	//将请求绑定到Teacher类中的user属性
}
请求
<!--客户端的请求user对应Teacher类的user属性,userName对应User类的属性-->
<form action="" method="post">
	<input name="user.userName" value="xxx"/>
</form>
Controller

@RequestMapping("test_pojo")
//参数绑定:将请求绑定到Teacher类的user属性中
public String test_pojo(Teacher t) throws Exception{
	System.out.println(t.getUser().getUserName());
	return null;
}


3、绑定List集合

pojo类及pojo包装类

//pojo类
public class Address{
	private String addr;
}
//pojo包装类
public class User{
	List<Address> address;
}
请求

<!--客户端的请求address是pojo包装类的属性名,addr是pojo的属性,因为是List,所以有下标-->
<form action="" method="post">
	<input name="address[0].addr" value="xxx"/>
	<input name="address[1].addr" value="xxx"/>
	<input name="address[2].addr" value="xxx"/>
</form>
Controller类

@RequestMapping("test_list")
public String test_list(User u) throws Exception{
	List<Address> addrList = u.getAddress().getAddr();
	return null;
}

4、映射Map

pojo以及包装类

public class Name{
	private String firstName;
	private String lastName;
}
public class User{
	Map<String,Name> nameMap;
}
Controller

@RequestMapping("...")
//参数类型为pojo包装类
public String test_map(User u) throws Exception{
	//代码简写
	System.out.println(u.getNameMap());
	return null;
}
请求

<!--
	nameMap:pojo包装类型的Map属性名
	['x'],['y']:Map<String,Name>中的String,代表key
	firstName,lastName:Name中的属性
-->
<form action="..." method="post">
	<input type="text" name="nameMap['x'].firstName"/>
	<input type="text" name="nameMap['x'].lastName"/>
	<input type="text" name="nameMap['y'].firstName"/>
	<input type="text" name="nameMap['y'].lastName"/>
</form>

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值