Play Framework で「Hello World!!」

Play Framework の環境構築については、

id: hidemium の下記記事を参照されたい。



Play Framework(Java)の開発環境を構築する - hidemium's blog

上記手順でEclipse 上にPlay Framework のプロジェクトが作成された状態からスタートする。

何はともあれ、お決まりの「Hello World !!」アプリを作っていこう。

作成したプロジェクトのappフォルダ以下のviews => index.scala.html を

以下の様に編集しよう。

■index.scala.html

@(message: String)

Hello World!!


上記コードを保存し下記URLでアクセスしてみよう。
http://localhost:9000/

これで、無事「Hello World!!」 が表示されたはずだ。
Play Framework の世界へようこそ。

ところで、何も説明せずに「Hello World!!」を作ってみたが、簡単に処理の流れを説明する。

まず、ユーザのhttp://localhost:9000/に対するリクエストがどの様に処理されるかを順を追って説明する。

(1) フレームワークの入口はroutesファイル
ユーザのhttp://localhost:9000/に対するリクエストにより、どのようなプログラムが呼び出されるかは、
routes ファイルを見れば分かる。
Java EE 開発の経験があるならば、このroutes ファイルが web.xml に相当するものと理解して良い。

プロジェクトフォルダ => app => conf => routes ファイルを参照すると、
下記の記載があるはずだ。

■routes

GET     /                           controllers.Application.index()

"/" つまり、http://localhost:9000/にアクセスした場合、「controllers.Application.index()」を呼び出すと
読むことができる。

次に「controllers.Application.index()」がどこで実装されているかを説明する。

(2) リクエストの受け手(Controller)
app => controllers => Application.java を見て欲しい。

package controllers;

import play.*;
import play.mvc.*;

import views.html.*;

public class Application extends Controller {

    public static Result index() {
        return ok(index.render("Your new application is ready."));
    }

}


当該クラスで index() というメソッドが定義されている。つまり、先ほどのroutes ファイルに従って呼び出されるメソッドは、このApplication.index()メソッドとなる。

つまり、
http://localhost:9000/
というURLでアクセスするとApplication.index()メソッドが呼び出される流れとなる。

(3) ブラウザへ表示するためのView
Application.index() の下記記載を見て欲しい。

return ok(index.render("Your new application is ready."));

上記行により、ブラウザで表示するHTMLを作成するプログラム(View)の「index.scala.html」が呼び出され、その結果ブラウザ上に「Hello World!!」が表示されるのである。

■index.scala.html

@(message: String)

Hello World!!

(4) Controller からView への値の受け渡しについて
下記コードのindex.render(***)の引数を見て欲しい。ここで、"Your new application is ready." という文字列をView に渡している。

return ok(index.render("Your new application is ready."));

それでは、この文字列をView 側で受け止めて表示してみよう。下記の通りView を編集する。

■index.scala.html

@(message: String)

@message <br>
Hello World!!


同様にhttp://localhost:9000/にアクセスしてみよう。
すると、ブラウザに"Your new application is ready."の文字列が表示されるはずだ。
View 側では、
@(message: String)
で、コントローラ側からString 型の文字列を受け取り、message という変数に代入する。

そして、@message により代入した(コントローラから渡された)文字列を出力する。

ここで、お気づきだろうが、Play Framework ではView はScala で記載される。
@で始まる文字列はPlay Framework により、Scala 文法に従って解釈される。
Java EE 開発におけるJSP に相当するものである。


以上が、Play Framework における処理の流れである。
Java EE開発とは少々勝手が違うが、今後より複雑なアプリを作成することでPlay Framework の開発手法に慣れて欲しい。