jsp通过logic:iterate或html:optionsCollection循环显示action中传过来的对象List

时间:2022-03-28 19:14:26
action中代码如下:
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->        List allUser=this.getLoginServiceImpl().find();
        request.setAttribute(
"user", allUser);
        
return mapping.findForward("listUser");
注:其中User对象有id和name属性

jsp显示:法一
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->            <html:select property="school">
            
<html:option value="">
                
<bean:message key="login.select" />
           
</html:option>
                
<logic:present name="user">
                    
<logic:iterate id="user" name="user" offset="0">
                        
<option value="<bean:write name="user" property="id" />">
                            
<bean:write name="user" property="name" />
                        
</option>
                    
</logic:iterate>
                
</logic:present>
        
</html:select>
jsp显示:法二
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->       <html:select property="school">
           
<html:optionsCollection name="user" value="id" label="name"/>
       
</html:select>

optionsCollection标签用法:
与options标签一样,optionsCollection标签可以从集合或者是包含集合的对象里获得选项的标签/值对。在这两种情况里,集合或包含集合的对象必须是一个作用域对象,否则定制标签将无法访问它。

1.与包含集合的对象配合使用
举例:userForm动作表单有一个如下所示的ArrayList类型的userList属性,相应的set,get方法,通过在action中设置好userForm后,request.setAttribute("userForm",userForm);
在jsp页面:
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><html:select property="school">
<html:optionsCollection name="userForm"
      property
="userList"/>
</html:select>

2.与集合配合使用
action中
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->ArrayList userList=new ArrayList();
userList.add(
new LabelValueBean("1","haha"));
userList.add(
new LabelValueBean("2","dada"));
userList.add(
new LabelValueBean("3","xiaoxiao"));
request.setAttribute(
"userList",userList);
jsp页面
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><html:select property="school">
<html:optionsCollection name="userList"
      label
="label" value="value"/>
</html:select>