How to “logic:iterate” just one object?

和自甴很熟 提交于 2019-12-06 16:41:10

You can use a bean name with the <logic:iterate>, but it should be a collection or array, or implement Iterable. Here's the example of the tag usage.

In Struts, you can use logic:iterate tag to iterate over collections. Here’re the example:

Iterate over a list/array (Object)

Create a normal list with few "user" objects and store it into HttpServletRequest as name "listUsers".

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");
  }

}

Inside the logic tag, you can use the "name" attribute (listUsers) to get the list value, while "property" attribute to display the object property value.

<%@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>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!