Strutsでは、
<logic:iterate>
タグを使用してコレクションを反復処理できます。ここに2つの例があります:
-
リストを反復する(プリミティブ型)
-
リスト(オブジェクト)を繰り返し処理する
1.リスト配列を反復処理する(プリミティブ型)
いくつかのダミーStringを持つ通常のリストを作成し、 “ listMsg ** ‘という名前の `HttpServletRequest`にそれを格納します。
... パブリッククラスPrintMsgActionはアクション{ public ActionForward execute(ActionMappingマッピング、ActionFormフォーム、 HttpServletRequestリクエスト、HttpServletResponseレスポンス) 例外をスローする{ リスト<String> listMsg = new ArrayList <String>(); listMsg.add( "メッセージA"); listMsg.add( "メッセージB"); listMsg.add( "メッセージC"); listMsg.add( "メッセージ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"%> <html> <head> </head> <body> <h1> Struts <logic:iterate>例</h1> <logic:iterate name = "listMsg" id = "listMsgId"> <p> メッセージの一覧表示<bean:write name = "listMsgId"/> </p> </logic:iterate> </body> </html>
2.リスト配列(オブジェクト)を繰り返し処理する
「ユーザー」オブジェクトがほとんどない通常のリストを作成し、それを
「
listUsers
」という名前で `HttpServletRequest`を呼び出します。
public class User { 文字列のユーザー名。 String url; //getterメソッドとsetterメソッド }
... 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"); } }
ロジックタグ内では、 ”
name
“属性(listUsers)を使用してリストの値を取得できます。オブジェクト属性値を表示するには ”
property
“属性を使用します。
<%@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>