Struts2中Iterator的用法.Struts2.0中
参考?http://cid-5b53dd6021f1c0ae.spaces.live.com/blog/cns!5B53DD6021F1C0AE!187.entry
以下内容属转载:
一.关于iterator迭代集合对象的问题:
Action 中大概是这样:
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import com.mingda.model.Chargecode_info;
import com.mingda.model.Timereport_info;
import com.mingda.service.Timereport_infoService;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.Preparable;
public class Timereport_infoAction implements Preparable{
//我只将页面中iterator能用到的变量写出来,其余的省略
private List
private List
private Timereport_info timereport_info;
private LinkedHashMap timereportinfo_view;
public Timereport_infoAction(Timereport_infoService service){ //Timereport_infoService是业务处理的接口类
this.service = service;
}
public String searchChargeCode(){ //页面上查询功能所调用的方法,结果返回的是每天的工作时间记录
….
timereportinfo_view = new LinkedHashMap
//说明一下,查询数据库中每一天的数据,因为每天数据可能有多条工作时间记录,所以我用 List来装这些记录并作为LinkedHashMap的值,
把每天的日期(String类型)作为LinkedHashMap的键。
….
List
timereportinfo_view.put(date, temp);
…..
//省略get set 方法
}
用图解的方式说明一下timereportinfo_view这个Map中数据的存放形式
/ [1] ——List{#a,#b}
/ [2] ——List{#a,#b,#c}
timereportinfo_view—— ….
(map) \ ….
\ [15]——List{#a,#b}
[1]到[15]表示1号到15号,是键。List是值。#a表示存放在List中第一条记录的对象,#b表示存放在List中第二条记录的对象,以此类推。
以下开始举例说明:
问题一:timereportinfo_view(LinkedHashMap类型的),而且timereportinfo_view嵌套了List,我需要的记录是存放在List当中的,那我在jsp页面中如何使用
iterator标签才能得到正确的记录呢?
答:
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page pageEncoding="utf-8" %>
<%@ taglib prefix="s" uri="/struts-tags"%>
问题二:如果是两个map嵌套应该如何用标签iterator迭代?
答:
问题三:在jsp页面上java代码部分用List存放了一些数据如何将List赋值给iterator,像这样:
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page pageEncoding="utf-8" %>
<%@ taglib prefix="s" uri="/struts-tags"%>
….
<% List list=new ArrayList(); list.add(string);%>
…..
//do some thing
答:
如果这么写
<%@ page pageEncoding="utf-8" %>
<%@ taglib prefix="s" uri="/struts-tags"%>
…..
<% List list=new ArrayList();
list.add(string);
request.setAttribute("list", list); %>
…….
…
问题四:iterator嵌套循环中,我想把外层循环中的某一值和内层循环中某一值作比较,如何实现?
错误示例 :
//do something
这里程序会报错,主要因为在内层中top所遍历的是当前的集合而且与同是当前集合中charge_code_id的有冲突。
解决方法:
当然可以互换里层与外层循环
//do something
这样top指向当前的集合#request.list,并可以遍历其值。但是这不是我们的初衷,在原来的结构不变的情况下如何实现呢?
很简单用
//do something
用top遍历集合”#request.list” 时每次得到的值先存放在
另附status的属性:
Here we use the IteratorStatus determine every fourth row to insert an extra line break.
even : boolean – returns true if the current iteration is even
odd : boolean – returns true if the current iteration is odd
count : int – returns the count (1 based) of the current iteration
index : int – returns the index (0 based) of the current iteration
first : boolean – returns true if the iterator is on the first iteration
last : boolean – returns true if the iteration is on the last iteration
modulus(operand : int) : int – returns the current count (1 based) modulo the given operand