Scala Play 2.0(3) MVCのルーティングとコントローラのつづき

先週の続き。

・リダイレクト

routesがこう

GET     /redirect1  controllers.SampleController.redirect1

GET    /redirect2  controllers.SampleController.redirect2

 で、controllerがこう。

def redirect1 = Action {

  Redirect("/sample2");

}

def redirect2 = Action {

  Redirect("http://www.example.com");

}

ヘルパ関数さまさまだね。

・スタブ

routesは一緒でcontrollerに

def something = TODO

 と書くだけでメソッドスタブになる。Action not implemented yet.とかでてくる。ユニットテストで超便利。

・パラメータ

色々と書き方がある。まずはroutesで

GET /sample3/:id  controllers.SampleController.sample3(id:Long)

と書くと、 REST風に与えられたパラメータ:idがコントローラsample3のLong型の引数として代入されてくる。

/sample3/1 →sample3(id:Long)のidが1

もちろん、数値としてパースできない文字列を与えるとエラーに。

つづいてはroutesに

GET  /sample3_5  controllers.SampleController.sample3_5(id:Long)

 でget query経由で指定できる。つまり、/sample3_5?id=2でsample3_5(id:Long)のidが2に。

任意の文字列もパスとして指定可能。routesに

GET /sample4/*path controllers.SampleController.sample4(path:String)

で/sample4/以降の文字列がpathとして代入されてくる。

また、一番最初のREST風で正規表現が利用可能。

GET /sample4_5/$id<[0-9]+> controllers.SampleController.sample4_5(id:Long

 まあ、この場合、1番めではOKだったマイナス値がvalidation errorになるけど、idだから負の値はないだろ的な思想なのでしょう。

今日はカレー作ったりしていそがしかったからこれだけです。