A.Controller
Play使用 Controllers來實現MVC結構,是用來連接服務器業務邏輯和前臺瀏覽器HTTP請求(HTTP requests)的橋樑。controller其實是一個繼承了父類play.mvc.Controller的類,在該類中定義了多個action的方法,該類位於controllers包中.
import play.*; import play.mvc.*; import views.html.*; public class Application extends Controller { public static Result index() { return ok(index.render("Your new application is ready.")); } }
---Action 和 Result
每個action是一個JAVA方法,用於處理HTTP的請求並將處理結果發還給用戶(Action可以看作是一個處理請求數據併產生一個結果放回給客戶端的簡單Java方法)
每個action方法的返回值類型均爲Result(play.mvc.Result),每個Result均對應一個HTTP請求(HTTP response),代表Http響應發送到客戶端,即
play.mvc.Results
類提供了多個helpers來產生標準的HTTP迴應,如ok()構建了一個200狀態的相應,它包含一個text/plain的響應體Results即結果。最簡單的莫過於包含一個狀態碼、一組HTTP頭和一個Http體的被髮送到web客戶端的Http Resul。這些Results被play.mvc.Result定義,play.mvc.Results 類提供了一些幫助產生標準Http Results的方法,下面的代碼示例創建了各種Results:
public static Result index() {
return ok("Hello world!");
}
//------------------------------------------------
Result ok = ok("Hello world!");
Result notFound = notFound();
Result pageNotFound = notFound("<h1>Page not found</h1>").as("text/html");
Result badRequest = badRequest(views.html.form.render(formWithErrors));
Result oops = internalServerError("Oops");
Result anyStatus = status(488, "Strange response type");
//------------------------------------------------------
// 重定向同樣是簡單的Results,把瀏覽器重定向到一個新的URL也不過是一種簡單的result,不同的是這些result 類型沒有響應體
public static Result index() {
return redirect("/user/home");
}
//-------------303-----------------------------------
public static Result index() {
return temporaryRedirect("/user/home");
}
//-------------GO_HOME Result-----------------------------------
public static Result GO_HOME = redirect(
routes.Application.list(0, "name", "asc", "")
);
public static Result index() {
return GO_HOME;
}
(Status code: ok -- 200, error, redirect, 404)
Result 返回值類型的使用:
在java----
public static Result create() { Form<Car> cForm=Form.form(Car.class); return Results.ok(create.render(cForm)); }
在html:
<a href="@routes.Cars.create()">Cancel</a>
當我們在瀏覽localhost:9000時,內部機制:
B--HTTP routing即綁定HTTP參數到JAVA方法(action)裏的參數
路由route是將每一個進來的Http請求轉換成一個Action調用(action是contoller類裏的靜態的、公共的方法)的組件。
路由在conf/routes文件中被定義,並且會被編譯,也就是說你能直接在瀏覽器中看到路由錯誤
路由有一定的優先級,通常會優先使用定義在route文件中的第一個路由。
Route(靜態路徑)語法含義:
GET /cars/create controllers.Cars.create()
GET---http方法,通常有PUT
, DELETE
, HEAD,GET和POST
/cars/create-----路徑定義,這個路徑會顯示在瀏覽器網址的localhost/後邊
controllers.Cars.create()----返回的action
PS 要考試了,好緊張,雖然不是很懂,但是還是操着一顆想完爆法國佬的野性吶= =Oo。