LoginSignup
1
2

More than 5 years have passed since last update.

[PlayFramework] 02. Actions, Controllers and Results

Posted at

Scalaの一番有名なフレームワークはPlay Frameworkである。

Play Frameworkに対して簡単に勉強しようと。

特に話がない内容はPlayFramework公式ホームページの内容を基に作成。

Actions, Controllers and Results

routes

// routes
GET / controllers.HomeController.index

http://localhost:9000に接続するとroutesによって、HomeControllerのindex関数が実行される。

Action(Controllers)

ほとんどのRequestはActionによってハンドルされる。

play.api.mvc.Actionは基本的に(play.api.mvc.Request => play.api.mvc.Result)関数である。

Requestをハンドルした後、処理の結果をClientに返す。

// HomeController.scala
def index = Action {
    implicit request => Ok(views.html.index())
}

index関数はRequestに対して、200OKとindex.scala.htmlを返す。

Templates(Views)

// index.scala.html
@()
@main("title") {
    <h1>Index Page</h1>
    This is a index page.
}

// main.scala.html
@(title: String)(content: Html)
<!DOCTYPE html>
<html>
    <head><title>@title</title></head>
    <body>@content</body>
</html>

index.scala.htmlは、mail.scala.htmlのテンプレートに書く内容が書いてある。

Simple Result

HTTPのResultはSTATUS CODEと一緒に出る。

HTTPのHeaderとBodyを作成して、Clientに返してみようと。

Resultはplay.api.mvc.Resultに定義されている。

import play.api.http.HttpEntity
import akka.util.ByteString

def index = Action {
    implicit request => Result(
        header = ResponseHeader(200, Map.empty),
        body = HttpEntity.Strict(ByteString("Hello world!"), Some("text/plain"))
    )
}

様々なResultがあるので、確認を。

val ok = Ok("Hello world!")
val notFound = NotFound
val pageNotFound = NotFound(<h1>Page not found</h1>)
val badRequest = BadRequest(views.html.form(formWithErrors))
val oops = InternalServerError("Oops")
val anyStatus = Status(488)("Strange response type")

Redirect

def index = Action {
    implicit request => Redirect("/", MOVED_PERMANENTLY)
}
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2