Skip to content

Instantly share code, notes, and snippets.

@mumoshu
Created November 25, 2011 10:58
Show Gist options
  • Save mumoshu/1393258 to your computer and use it in GitHub Desktop.
Save mumoshu/1393258 to your computer and use it in GitHub Desktop.
Play 2.0 betaのAPIメモ
import play.api.WS
import play.api.mvc.Controller
object Posts/*名詞複数形*/ extends Controller {
/**
* "Hello Play 2.0!"という文字列を返すアクション
* argがパラメータとして指定されていなければ、Playにより400 BAD REQUESTが返される。
*/
def index/*アクション名*/(arg: String /*リクエストパラメータ*/) = Action {
Ok("Hello Play 2.0!")
}
/**
* ビューテンプレートをつかうアクション
* app/views/templateExample.scala.html に引数を一つとるテンプレートを定義した場合はこのように呼び出す。
*/
def templateExample = Action {
views.html.templateExample("the first argument passed to the template")
}
/**
* Playの非同期処理の仕組みをつかったアクション
* google.co.jpトップのHTMLからbody要素のテキストを抜き出して表示する。
* google.co.jpへのHTTP通信中にHTTPリクエストを裁くスレッドをブロックしないところがポイント。
*/
def nonBlocking = Action {
AsyncResult {
WS.url("http://www.google.co.jp")
.get() // : Promise[com.ning.http.client.Response]
.map(_.getResponseBody) // : Promise[String]
.map(scala.xml.XML.loadString) // : Promise[scala.xml.Elem]
.map(_ \\ "body" text) // : Promise[String]
.map { bodyAsStr =>
Ok(bodyAsStr).withHeaders(CONTENT_TYPE -> "text/plain; charset=UTF-8")
} // : Promise[Result]
}
}
//
// 利用できるResultのファクトリ
//
// Ok
// Unauthorized
// NotFound
// Forbidden
// BadRequest
// InternalServerError
// NotImplemented
// NotModified
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment