LoginSignup
0
1

More than 5 years have passed since last update.

[PlayFramework] 04. Manipulating Results

Posted at

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

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

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

Manipulating Results

基本的にContent-Typeは自動で変わる

def actionText = Action {
    implicit request => Ok("Hello, World!")
}

def actionXml = Action {
    implicit request => Ok(<message>Hello World!</message>)
}

Okのパラメータをパーシングして、actionTextはtext/plainに、actionXmlはapplication/xmlに処理する。

これに関するAPIはplay.api.http.ContentTypeOfクラスに書いてある。

Content-Typeを指定して、Responseを処理したい場合は下記のように作成。

def actionExplicitOne = Action {
    request => Ok(<h1>Hello World!</h1>).as("text/html")
}

def actionExplicitTwo =  Action {
    request => Ok(<h1>Hello World!</h1>).as(HTML)
}

HTTP Headerの操作

def actionManipulatingHeader = Action {
    implicit request => Ok("Hello World!").withHeaders(
        CACHE_CONTROL -> "max-age=3600",
        ETAG -> "xx"
    )
}

Cookieの生成、削除

CookieはHTTP Headerの特別なフォームである。

Helperを利用して簡単に操作ができる。

def createCookie = Action {
    implicit request => Ok("Create Cookie").withCookies(
        Cookie("customCookie", "this is cookie")
    )
}

def removeCookie = Action {
    implicit request => Ok("Remove Cookie").discardingCookies(DiscardingCookie("customCookie"))
}

def createRemoveCookie = Action {
    implicit request => Ok("Create And Remove Cookie").withCookies(
        Cookie("CreatedCookie", "OK")
    ).discardingCookies(
        DiscardingCookie("customCookie")
    )
}

HTTP Responseの文字のエンコーディングを変える

import play.api.mvc.Codec
class CustomController extends Controller {
    implicit val myCustomCharset = Codec.javaSupported("iso-8859-1")
}
0
1
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
0
1