Wicket Examples - guestbook編 -

「サンプルのソースを見る」の第6回guestbook編。このサンプルでは、

がなんとなくわかります(^_^;)。

アプリケーションクラス(GuestBookApplication.java)

まずは、アプリケーションクラスです。こちらは、ホームページクラスを返しているだけなので、割愛します。

Pageクラス(GuestBook.java)

次に、Pageクラスです。

public final class GuestBook extends WicketExamplePage
{

Commentインスタンスを格納するリスト(commentList)と、ListViewです。commentListがstaticとなっており、全ユーザからの情報が追加・参照されるようです。

	private static final List commentList = new ArrayList();
	private final ListView commentListView;

コンストラクタでは、Formのインスタンスを追加し、ListViewコンポーネントインスタンスを追加しています。populateItemメソッドでは、入力内容であるCommentインスタンスの、日付をLabelコンポーネントに、入力テキストをMultiLineLabelコンポーネントに設定しています。setVersionedメソッドを引数をfalseで呼び、バージョニングをしないようにしています・・・なんのことやらですが(^_^;)

	public GuestBook()
	{
		add(new CommentForm("commentForm"));

		add(commentListView = new ListView("comments", commentList)
		{
			public void populateItem(final ListItem listItem)
			{
				final Comment comment = (Comment)listItem.getModelObject();
				listItem.add(new Label("date", new Model(comment.getDate())));
				listItem.add(new MultiLineLabel("text", comment.getText()));
			}
		}).setVersioned(false);
	}

次にFormコンポーネントです。

	public final class CommentForm extends Form
	{

コンストラクタでは、スーパークラスのコンストラクタを呼んで、TextAreaコンポーネントを追加しています。

		public CommentForm(final String id)
		{
			super(id, new CompoundPropertyModel(new Comment()));
			add(new TextArea("text"));
		}

Submitボタンが押下された時に呼ばれるonSubmitメソッドをオーバーライドします。モデルオブジェクトであるCommentクラスのインスタンスを取得し、それをもとに新たなCommentインスタンスを生成します。生成したインスタンスに現在の日付を設定して、commentListの先頭に追加するわけですが、追加する前にListView#modelChangingメソッドを、追加したあとにListView#modelChangedメソッドを呼ぶことで、ListViewに反映を通知しているようです。

		public final void onSubmit()
		{
			// Construct a copy of the edited comment
			final Comment comment = (Comment)getModelObject();
			final Comment newComment = new Comment(comment);

			// Set date of comment to add
			newComment.setDate(new Date());

			// Add the component we edited to the list of comments
			commentListView.modelChanging();
			commentList.add(0, newComment);
			commentListView.modelChanged();

			// Clear out the text component
			comment.setText("");
		}
	}

Beanクラス(Comment.java)

次に、Beanクラスです。コメントと日付を持つクラスです。

public class Comment implements Serializable
{

HTMLテンプレートファイル(GuestBook.html)

最後に、HTMLテンプレートファイルです。

ListViewコンポーネントです。今までに入力された内容を、最新のものからここに表示します。表示内容は、日付と入力されたコメントです。

  
    

1/1/2004
Comment text goes here.

あと、wicket:remove要素があるのですが、実行には消されるようです。表示確認用ですかねぇ?

  <wicket:remove>
    <p>
	    1/2/2004<br/>
	    More comment text here.
    </p>
  </wicket:remove>