java - 如何 "logic:iterate"只是一个对象?

标签 java jsp collections struts javabeans

所以,我有这个代码:

logic:iterate name="nameForm" property="name" id="nameId" indexId="index"
bean:write name="nameId" property="field1"/
bean:write name="nameId" property="field2"/

这非常有效,因为我收到了一个“对象表”,这样我就可以毫无问题地进行迭代。

现在,在另一个页面上我需要执行相同的操作,但问题是我没有收到“对象表”,而是收到一个对象本身。 尽管如此,我还是尝试了它 - 正如预期的那样 - 收到错误:无法为此集合创建迭代器

我已经做过 RTFM,但我仍然比以前更困惑。
我知道“logic:iterate”中的“name”如何指向 struts-config 中的表单名称,现在我需要仅使用一个 bean 执行相同操作,请提供帮助吗?

最佳答案

您可以使用带有<logic:iterate>的bean名称,但它应该是一个集合或数组,或实现 Iterable Here是标签使用的示例。

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>

enter image description here

关于java - 如何 "logic:iterate"只是一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34788885/

相关文章:

view - 从NS文档目录加载图像时, Collection View 崩溃

java - Spring:创建名为 'entityManagerFactory' 的 bean 时出错,原因是:java.lang.AbstractMethodError:null

java - 在android中存储少量数据

java - 使用 plusMinutes 添加分钟时出现问题

java - 如何更正 JSP 中的 servlet 映射?

c# - 无法将 null 添加到可空列表

java - 有没有办法在远程调试期间搜索堆栈中当前位置可用的变量?

java - Action 上的字符编码 URLDecoder

java - 访问 Struts 2 中的所有用户 session

php - 通过数据映射器处理集合模式中的项目