Changing the default Content-Type 改变默认内容类型
The result content type is automatically inferred from the Java value you specify as body.
result的内容类型会根据你指定的java值自动推断出来
For example:
例如:
Result textResult = ok("Hello World!");
Will automatically set the Content-Type header to text/plain, while:
这将会自动的设置内容类型为 text/plain,而:
Result jsonResult = ok(jerksonObject);
will set the Content-Type header to application/json.
将会设置内容类型为 application/json.
This is pretty useful, but sometimes you want to change it. Just use theas(newContentType) method on a result to create a new similiar result with a different Content-Type header:
这是十分有用的,如果你想改变它,只需要调用as(newContentType) 方法来创建一个新的result:
Result htmlResult = ok("<h1>Hello World!</h1>").as("text/html");
You can also set the content type on the HTTP response:
你也可以设置HTTP应答的内容类型。
public static Result index() {
response().setContentType("text/html");
return ok("<h1>Hello World!</h1>");
}
You can add (or update) any HTTP response header:
你可以添加(或更新)任何HTTP应答头:
public static Result index() {
response().setContentType("text/html");
response().setHeader(CACHE_CONTROL, "max-age=3600");
response().setHeader(ETAG, "xxx"); return ok("<h1>Hello World!</h1>");
}
Note that setting an HTTP header will automatically discard any previous value.
注意 设置HTTP头会覆盖当前的值。
Cookies are just a special form of HTTP headers, but Play provides a set of helpers to make it easier.
Cookies只不过是HTTP头的特定格式,但是play 提供了一系列便利方法:
You can easily add a Cookie to the HTTP response:
你可以很容易给HTTP应答添加一个Cookie:
response().setCookie("theme", "blue");
Also, to discard a Cookie previously stored on the Web browser:
你也可以删除已有的Cookie:
response().discardCookies("theme");
For a text-based HTTP response it is very important to handle the character encoding correctly. Play handles that for you and uses utf-8 by default.
正确的处理字符编码对于文本类型的HTTP应答是非常重要的,Play默认用 utf-8 .
The encoding is used to both convert the text response to the corresponding bytes to send over the network socket, and to add the proper ;charset=xxx extension to the Content-Type header.
编码即用于把文本应答转换成相应的网络字节码,也为内容类型头添加恰当的 ;charset=xxx 扩展
The encoding can be specified when you are generating the Result value:
你可以在生成 Result 值的时候指定编码:
public static Result index() {
response().setContentType("text/html; charset=iso-8859-1");
return ok("<h1>Hello World!</h1>", "iso-8859-1");
}