Change the default content type
Depending on the Scala value specified in the response body, the content type of the result can be inferred automatically, for example:
val textResult = Ok("Hello World!")
This will automatically set the Content-type's head totext/plain,同时:
val xmlResult = Ok(<message>Hello World!</message>)
This will set the head toapplication/xml
Above throughplay.api.http.ContentTypeOf这个类来实现。用as(newContentType)可以强制转换header的content type,
val htmlResult = Ok(
Or as follows:
val htmlResult2 = Ok(
UseHTML类型,头部会被自动设置成text/html; charset=utf-8。
You can add an HTTP header to the result:
val result = Ok("Hello World!").withHeaders(
CACHE_CONTROL -> "max-age=3600",
ETAG, "xx")
Cookies are a special form of HTTP headers that make it easier to use a series of helper classes. Add cookies to the HTTP response:
val result = Ok("Hello world").withCookies(
Cookies ("Theme", "Blue"))
Discard cookies stored by the browser:
val result2 = result.discardingCookies(DiscardingCookie("theme"))
The two can also be mixed:
val result3 = result.withCookies(Cookie("theme", "blue")).discardingCookies(DiscardingCookie("skin"))
Change the character set of the HTTP response of a text type
HTTP response is used by defaultutf-8
The character set is not only used to convert text responses into corresponding byte streams for network transmission, but also with ";charset=xxx"来更新content-type头部。
Passplay.api.mvc.Codec这个类,字符集被自动处理。在当前范围内,导入play.api.mvc.Codec这个隐式类可以更改字符集,用以下的方式操作:
class Application extends Controller {
implicit val myCustomCharset = Codec.javaSupported("iso-8859-1")
def index = Action {
Ok( }
}
About the definition of HTML:
def HTML(implicit codec: Codec) = {
"text/html; charset=" + codec.charset
}
Scala Next play Framework learning Note (manipulating Results)