Struts 例

在Struts中,可以使用<logic:iterate>标记遍历集合。 这是两个例子:

  1. 遍历列表(原始类型)
  2. 遍历列表(对象)

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 &lt;logic:iterate&gt; 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 &lt;logic:iterate&gt; 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-logic-iterate-example

下载源代码

下载它– Struts-logic-Iterate-example.zip

翻译自: https://mkyong.com/struts/struts-logic-iterate-example/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值