play2.0文檔-面向java開發者(3)

Manipulating the response 處理應答


Changing the default Content-Type 改變默認內容類型html


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

result的內容類型會根據你指定的java值自動推斷出來json

 

For example:cookie

例如:網絡

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


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

這將會自動的設置內容類型爲 text/plain,而:ide

 

Result jsonResult = ok(jerksonObject);編碼


will set the Content-Type header to application/json.spa

將會設置內容類型爲 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>");

}

Setting HTTP response headers 設置HTTP應答頭


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頭會覆蓋當前的值。

 

Setting and discarding cookies 設置和刪除cookies


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");


Specifying the character encoding for text results

指定文本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.

正確的處理字符編碼對於文本類型的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");

}

相關文章
相關標籤/搜索