play framework2学习之旅<2.3>Manipulating the response

Manipulating the response(处理响应)

这一节的内容比较简单,所以简单浏览一遍即可,大概留个印象,估计暂时不会用到,在处理文件上传下载时应该会用到一些,到时候再查哈,所以等遇到了再去查即可,另一种哲学观:很少用&能查到的内容,不要背!

Changing the default Content-Type

The result content type is automatically inferred from the Java value you specify as body.

For example:

Result textResult = ok("Hello World!");

Will automatically set the Content-Type header to text/plain, while:

Result jsonResult = ok(jerksonObject);

will set the Content-Type header to 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:

Result htmlResult = ok("<h1>Hello World!</h1>").as("text/html");

You can also set the content type on the HTTP response:

public static Result index() {
  response().setContentType("text/html");
  return ok("<h1>Hello World!</h1>");
}

Setting HTTP response headers

You can add (or update) any HTTP response header:

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.

Setting and discarding cookies

Cookies are just a special form of HTTP headers, but Play provides a set of helpers to make it easier.

You can easily add a Cookie to the HTTP response:

response().setCookie("theme", "blue");

Also, to discard a Cookie previously stored on the Web browser:

response().discardCookies("theme");

Specifying the character encoding for text results

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.

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.

The encoding can be specified when you are generating the Result value:

public static Result index() {
  response().setContentType("text/html; charset=iso-8859-1");
  return ok("<h1>Hello World!</h1>", "iso-8859-1");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值