1.封装到List
a. 编写测试页面login4.jsp:
<%@ 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>Insert title here</title>
</head>
<body>
<h1>演示参数封装到list</h1>
<form action="login4.action" method="post">
用户名1:<input type="text" name="users[0].username"><br>
密码1:<input type="password" name="users[0].password"><br>
用户名2:<input type="text" name="users[1].username"><br>
密码2:<input type="password" name="users[1].password"><br>
用户名3:<input type="text" name="users[2].username"><br>
密码3:<input type="password" name="users[2].password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
编写Login4Action类:
public class Login4Action extends ActionSupport{
private static final long serialVersionUID = 1L;
private List<User> users;//接收多个User对象
@Override
public String execute() throws Exception {
for (User user : users) {
System.out.println(user);
}
return NONE;
}
public void setUsers(List<User> users) {
this.users = users;
}
public List<User> getUsers() {
return users;
}
}
在struts.xml中配置Login4Action类:
<action name="login4" class="cn.icbc.action.Login4Action"></action>
测试结果如下:
2…封装到Map
注:查看jsp页面传入参数的name属性值得写法。
- 用户名1:
<input type="text" name="users['one'].username"><br>
新建login5.jsp页面:
<%@ 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>Insert title here</title>
</head>
<body>
<h1>演示参数封装到Map</h1>
<form action="login5.action" method="post">
用户名1:<input type="text" name="users['one'].username"><br>
密码1:<input type="password" name="users['one'].password"><br>
用户名2:<input type="text" name="users['two'].username"><br>
密码2:<input type="password" name="users['two'].password"><br>
用户名3:<input type="text" name="users['three'].username"><br>
密码3:<input type="password" name="users['three'].password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
新建Login5Action类:
package com.icbc.struts.study2;
import java.util.Map;
import java.util.Set;
import com.opensymphony.xwork2.ActionSupport;
public class Login5Action extends ActionSupport {
private static final long serialVersionUID = 1L;
private Map<String,User> users;
@Override
public String execute() throws Exception {
Set<String> keys = users.keySet();
for (String key : keys) {
System.out.println(key + ":" + users.get(key));
}
return NONE;
}
public Map<String, User> getUsers() {
return users;
}
public void setUsers(Map<String, User> users) {
this.users = users;
}
}
在struts.xml中配置Login5Action:
<action name="login5" class="cn.icbc.action.Login5Action"></action>
测试结果如下: