Struts <logic:iterate>例

Struts の例

Strutsでは、<logic:iterate>タグを使用してコレクションを反復処理できます。 以下に2つの例を示します。

  1. リストの繰り返し(プリミティブ型)

  2. リスト(オブジェクト)を反復処理する

1. リスト配列を反復します(プリミティブ型)

いくつかのダミー文字列を使用して通常のリストを作成し、「listMsg」という名前のHttpServletRequestに格納します。

...
public class PrintMsgAction extends Action{

    public ActionForward execute(ActionMapping mapping,ActionForm form,
        HttpServletRequest request,HttpServletResponse response)
        throws Exception {

        List listMsg = new ArrayList();

        listMsg.add("Message A");
        listMsg.add("Message B");
        listMsg.add("Message C");
        listMsg.add("Message D");

        request.setAttribute("listMsg", listMsg);

        return mapping.findForward("success");
    }

}

ロジックタグ内では、「name」属性(listMsg)を使用してリスト値を取得できます。

<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>




Struts example

List Messages

2. リスト配列(オブジェクト)を反復処理する

「ユーザー」オブジェクトがほとんどない通常のリストを作成し、「listUsers」という名前でHttpServletRequestに保存します。

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 listUsers = new ArrayList();

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

}

ロジックタグ内で、「name」属性(listUsers)を使用してリスト値を取得できます。一方、「property」属性は、オブジェクトのプロパティ値を表示します。

<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>




Struts example

List Users ,

struts-logic-iterate-example

ソースコードをダウンロード

ダウンロード–Struts-logic-Iterate-example.zip