Home > プログラミング > [Struts]ArrayListオブジェクトの各要素をJSPで扱う

[Struts]ArrayListオブジェクトの各要素をJSPで扱う

ActionFormの属性として定義したArrayListオブジェクトの各要素を、JSPで表示&取得する方法を学んだのでメモ。

以下のページを参考にさせていただきました。ありがとうございます!

ActionForm

public class TestForm extends ActionForm {
	private List tags = new ArrayList();
	
	// このメソッドが必要	
	public Tag getTag(int index) {
		while (this.tags.size() <= index) {
			this.tags.add(new Tag());
		}
		return (Tag)this.tags.get(index); 
	}
	
	public List getTags() {
		return tags;
	}
	public void setTags(List tags) {
		this.tags = tags;
	}
}

tagsというArrayList型のオブジェクトを属性として持つTestFormクラスです。

getTag(int index)メソッドが必要みたいです。

ArrayListが格納するオブジェクトのクラス

public class Tag{
	private String name;
	private String locale;
	public String getLocale() {
		return locale;
	}
	public void setLocale(String locale) {
		this.locale = locale;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

ArrayListが格納するオブジェクトのクラスです。
localeという謎の属性を持っていますが気にしないでください。

Action

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

		TestForm form = new TestForm();
		form.getTag(0);
		request.setAttribute("TestForm", form);
		
		return mapping.findForward("success");
	}
}

ArrayListオブジェクトの各要素を扱うJSPを呼び出すためのActionクラスです。

「form.getTag(0)」でActionFormのArrayListに一つ要素を加えています。

こうしないと、下のJSPが呼び出されたときにテキストボックスが表示されません。

JSP

<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib uri="/tags/struts-logic" prefix="logic" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>

<html:html>
<body>
<html:form action="/RegistForm">
<logic:iterate id="tag" name="TestForm" property="tags" indexId="index">
<html:text name="tag" property="name" indexed="true"/>
<html:text name="tag" property="locale" indexed="true"/>
</logic:iterate>
<html:submit value="登録"/>
</html:form>
</body>
</html:html>

ArrayListに格納された要素の数だけテキストボックスが表示されます。

まとめ

駄目だ、ちゃんと説明できるほど理解できていません。

「どうしてActionFormにgetTag(int index)メソッドが必要なのか?」などなど・・

ここはこうした方が良いとか、ここは間違っているとかあればコメント頂けるとうれしいです。

Comments:2

civic 2008年2月16日 10:41

>「どうしてActionFormにgetTag(int index)メソッドが必要なのか?」などなど・・
実行結果のHTMLを見てみると分かりますよ。


nameが”tag[0].name"というように出力されます。このリクエストがStrutsに渡ると、Strutsは次のように判断してActionFormにsetしてくれるのです。
tag[0].name  →   getTag(0)を実行し、返されたオブジェクトに対してsetName()する。

kadoppe Author Profile Page 2008年2月16日 13:26

>civicさん
なるほど、謎が解けました!
わからないまま放ったらかしにするのはよくない癖ですね・・・
ありがとうございました!

Comment Form

Trackbacks:0

TrackBack URL for this entry
http://www.kadoppe.net/mt/mt-tb.cgi/86
Listed below are links to weblogs that reference
[Struts]ArrayListオブジェクトの各要素をJSPで扱う from CreativeStyle

Home > プログラミング > [Struts]ArrayListオブジェクトの各要素をJSPで扱う

Search
Feeds

Return to page top