在Struts中,可以使用<logic:iterate>标记遍历集合。 这是两个例子:
- 遍历列表(原始类型)
- 遍历列表(对象)
1.遍历列表数组(原始类型)
用一些伪字符串创建一个普通列表,并将其存储到名称为“ listMsg ”的HttpServletRequest
。
...
public class PrintMsgAction extends Action{
public ActionForward execute(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response)
throws Exception {
List<String> listMsg = new ArrayList<String>();
listMsg.add("Message A");
listMsg.add("Message B");
listMsg.add("Message C");
listMsg.add("Message D");
request.setAttribute("listMsg", listMsg);
return mapping.findForward("success");
}
}
在逻辑标签内,可以使用“名称”属性(listMsg)获取列表值。
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<html>
<head>
</head>
<body>
<h1>Struts <logic:iterate> example</h1>
<logic:iterate name="listMsg" id="listMsgId">
<p>
List Messages <bean:write name="listMsgId"/>
</p>
</logic:iterate>
</body>
</html>
2.遍历列表数组(对象)
创建一个很少有“用户”对象的普通列表,并将其以“ listUsers ”的名称存储到HttpServletRequest
中。
public class User{
String username;
String url;
//getter and setter methods
}
...
public class PrintMsgAction extends Action{
public ActionForward execute(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response)
throws Exception {
List<User> listUsers = new ArrayList<User>();
listUsers.add(new User("user1", "http://www.user1.com"));
listUsers.add(new User("user2", "http://www.user2.com"));
listUsers.add(new User("user3", "http://www.user3.com"));
listUsers.add(new User("user4", "http://www.user4.com"));
request.setAttribute("listUsers", listUsers);
return mapping.findForward("success");
}
}
在逻辑标记内,您可以使用“ name ”属性(listUsers)获取列表值; 而“ property ”属性显示对象的属性值。
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<html>
<head>
</head>
<body>
<h1>Struts <logic:iterate> example</h1>
<logic:iterate name="listUsers" id="listUserId">
<p>
List Users <bean:write name="listUserId" property="username"/> ,
<bean:write name="listUserId" property="url"/>
</p>
</logic:iterate>
</body>
</html>
下载源代码
标签: Struts
翻译自: https://mkyong.com/struts/struts-logic-iterate-example/