guestbook#1
textareaに入力した値をDatasoreへ保存するまでを実装する。続きはguestbook#2で。
モデル作成
モデル生成
- build.xml -> gen-model タスク実行
- ダイアログに「guestbook.Entry」と入力
モデルに属性追加
package org.slim3tutorial.model.guestbook; public class Entry implements Serializable { : private String content; public String getContent() { return this.content; } public void setContent(String content) { this.content = content; } : }
サービス作成
サービス生成
- build.xml -> gen-service タスク実行
- ダイアログに「GuestbookService」と入力
サービス修正
package org.slim3tutorial.service; import com.google.appengine.api.datastore.Transaction; import java.util.Map; import org.slim3.datastore.Datastore; import org.slim3.util.BeanUtil; import org.slim3tutorial.model.guestbook.Entry; public class GuestbookService { public Entry entry(Map<String, Object> input) { Entry entry = new Entry(); BeanUtil.copy(input, entry); Transaction tx = Datastore.beginTransaction(); Datastore.put(entry); tx.commit(); return entry; } }
コントローラ修正
package org.slim3tutorial.controller.guestbook; import org.slim3.controller.Controller; import org.slim3.controller.Navigation; import org.slim3.util.RequestMap; import org.slim3tutorial.service.GuestbookService; public class IndexController extends Controller { @Override public Navigation run() throws Exception { GuestbookService service = new GuestbookService(); service.entry(new RequestMap(request)); return forward("index.jsp"); } }
動作確認
http://localhost:8888/guestbook/ の textarea にテキトーな文字列を入力し、submitする。
http://localhost:8888/_ah/admin/ の DataViewer にエントリが登録されているか確認する。
注意 モデル命名
ダイアログに「guestbook.Entry」と入力
としたが、「guestbook.Entry」と「hoge.Entry」はどちらも「Entry」というKindとしてデータストアに格納される。モデルのクラス名は重複しないように注意しよう。