Struts的Indexed属性用处
Struts的Indexed属性用处
banq http://www.jdon.com Mar 3, 2004 4:19 PM 回复
说明:这是Struts的一种高级用法,struts-el中有相关说明,这里讨论在一般struts标签库下如何实现。
场景:
有一个JavaBeans:如下:
publicclass LabelValueBean implements Serializable {
public LabelValueBean(String label, String value) {
this.label = label;
this.value = value;
}
private String label;
public String getLabel() {
returnthis.label;
}
publicvoid setLabel(String label) {
this.label = label;
}
private String value;
public String getValue() {
returnthis.value;
}
publicvoid setValue(String value) {
this.value = value;
}
public String toString() {
StringBuffer sb = new StringBuffer("LabelValueBean[");
sb.append(this.label);
sb.append(", ");
sb.append(this.value);
sb.append("]");
return (sb.toString());
}
}
这是非常普通的JavaBeans, 如果ActionForm是这样:
public class TestBean extends ActionForm {
.....
private List lvbeans = new ArrayList();
.....
}
lvbeans是LabelValueBean的集合,如此组合,如果需要在Jsp页面中对LabelValueBean的label和value值进行增删改,怎么办?
使用indexed属性,TestBean类如下:
public class TestBean extends ActionForm {
.....
private List lvbeans = new ArrayList();
public TestBean(){ //初始化数值
lvbeans.add( new LabelValueBean( "1" , "1" ));
lvbeans.add( new LabelValueBean( "2" , "2" ));
lvbeans.add( new LabelValueBean( "3" , "3" ));
}
public LabelValueBean getLvbeans( int index) {
return (LabelValueBean)lvbeans.get(index);
}
public List getLvbeans() {
return lvbeans;
}
.....
}
注意上述两个get方法很重要,Jsp页面代码如下:
<%@ taglib uri= "/WEB-INF/struts-logic.tld" prefix= "logic" %>
<%@ taglib uri= "/WEB-INF/struts-bean.tld" prefix= "bean" %>
<%@ taglib uri= "/WEB-INF/struts-html.tld" prefix= "html" %>
<jsp:useBean id= "test2" scope= "page" class= "test.TestBean" />
<h2>Test:
<logic:iterate name= "test2" property= "lvbeans" id= "foo" indexId= "ctr" >
<html:text name= "test2"
property='<%= "lvbeans[" + ctr + "].label" %>' />
</logic:iterate>
</h2>
这样,运行后的输出结果是:
<h2>Test:
<input type= "text" name= "lvbeans[0].label" value= "1" >
<input type= "text" name= "lvbeans[1].label" value= "2" >
<input type= "text" name= "lvbeans[2].label" value= "3" >
</h2>
这样修改TestBean中的List中的LabelValueBean数值了。