Play Framework で作る簡易認証システム(その3: ユーザ情報の表示)
前回に引き続き簡易認証システムを作っていく。
現状のつぶやき機能では誰が投稿したのかどうかわからないし、現在入っているユーザが誰なのかも分からない。
そこで、ログインしているユーザ情報と投稿者の情報を画面に表示するようにしよう。
"/inputchat"のリクエストを処理するApplication.inputchat()メソッドを下記の通り変更する。
セッション情報から"username"の内容を取得して、それをView に渡す。
■Application.inputchat()メソッド
@Security.Authenticated(models.Secured.class) public static Result inputchat() { //フォームを定義 Form<PostChatForm> postChatForm = new Form(PostChatForm.class); //grpchatテーブルの内容をselectし、Listに格納する。 List<Grpchat> grpchatAllRec = Grpchat.find.all(); //セッション情報"username"を取得 String username = session().get("username"); return ok(inputchat.render("InputChatForm",postChatForm, grpchatAllRec, username)); }
続いてViewを下記の通り編集する。
・コントローラからusernameを受け取る。
・フォームにおいて、hiddenでユーザ名を持たす。
■inputchat.scala.html
@(message: String, postchatform: Form[forms.PostChatForm], grpchatList:List[Grpchat],username: String) @import helper._ This resource is @message. こんにちは♪ <br> @username さん @form(routes.Application.postchat()) { @inputText(postchatform("postMessage")) <input type="hidden" name="username" value= "@username" > } @for(chatrec <- grpchatList){ @chatrec.message / @chatrec.postdate [@chatrec.username]<br> }
最後に上記フォームが投稿されたときに呼び出されるApplication.postchat()を編集する。
変更内容としては、フォームのusernameフィールドの内容をController 側で取得して
Grpchat オブジェクトに格納している点である。
■Application.postchat()
public static Result postchat(){ //フォームの内容を取得して、PostChatFormクラスのインスタンスに格納する。 Form<PostChatForm> postChatForm = new Form(PostChatForm.class).bindFromRequest(); //フォームの内容をpostMessageに代入する。 String postMessage = postChatForm.get().getPostMessage(); String postUsername = postChatForm.get().getUsername(); //Grpchat オブジェクトをインスタンス化 Grpchat grpchatRecd = new Grpchat(); //Grpchat オブジェクトのmessageフィールドにフォームで取得した内容をセットする grpchatRecd.setMessage(postMessage); //Grpchat オブジェクトのusernameフィールドにフォームで取得した内容をセットする grpchatRecd.setUsername(postUsername); //テーブルにデータを登録 grpchatRecd.save(); //return ok(postchat.render(postMessage)); return redirect("/inputchat"); }
ここまでできたら、
http://localhost:9000/inputchat
にアクセスして、grpchat テーブルのusernameカラムに投稿者のアカウント名が登録され、
投稿者、およびログインしているユーザ名が表示されることを確認しよう。