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。
转载于:https://blog.51cto.com/blackcat/1426430