- 2008年1月11日 23:11
- プログラミング
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)メソッドが必要なのか?」などなど・・
ここはこうした方が良いとか、ここは間違っているとかあればコメント頂けるとうれしいです。