PLAY2.6-SCALA(二) Actions, Controllers ,Results,routes

一、Action(play.api.mvc.Action)

大多数的应用的请求都是由action进行处理,并生成一个结果给客户端,Action有多种创建方式:

1.

Action {Ok("Hello world")}

2.

Action { request =>Ok("Got request [" + request + "]")}

3.

Action { implicit request =>Ok("Got request [" + request + "]")}

4.

def action = Action { implicit request =>
   anotherMethod("Some para value")
   Ok("Got request [" + request + "]")
 }
def anotherMethod(p: String)(implicit request: Request[_]) = { // do something that needs access to the request }

5.

Action(parse.json) { implicit request =>Ok("Got request [" + request + "]")}

6.空的响应

def index(name:String) = TODO

二、 controller

controller通常是生成Action值的对象,通常把它定义为一个类而不是一个对象,例如:

package controllers
import javax.inject.Inject
import play.api.mvc._
class Application @Inject()(cc: ControllerComponents)extends AbstractController(cc) {
  def index = Action {
    Ok("It works!")
  }
}

三、Result(play.api.mvc.Result)

1.带header和body的http结果

import play.api.http.HttpEntity

def index = Action {
  Result(
    header = ResponseHeader(200, Map.empty),
    body = HttpEntity.Strict(ByteString("Hello world!"), Some("text/plain"))
  )
}

其他的一些结果

val ok = Ok("Hello world!")
val notFound = NotFound
val pageNotFound = NotFound(<h1>Page not found</h1>)
val badRequest = BadRequest(views.html.form(formWithErrors))
val oops = InternalServerError("Oops")
val anyStatus = Status(488)("Strange response type")

2.重定向到一个新的URL

def index = Action {Redirect("/user/home", MOVED_PERMANENTLY)}

四、Routes(conf/routes)

主要包含http请求方式((GETPATCHPOSTPUTDELETEHEAD)和请求地址

1.动态请求地址

GET   /clients/:id          controllers.Clients.show(id: Long)

包含多层结构的地址

GET   /files/*name          controllers.Application.download(name)

/files/images/logo.png中*name代表的是 images/logo.png

带正则表达式的地址

GET   /items/$id<[0-9]+>    controllers.Items.show(id: Long)

2.函数参数

GET   /:page                controllers.Application.show(page)
GET   /                     controllers.Application.show(page)

第二个函数的参数,是请求到的内容

例子:

def show(id: Long) = Action {
  Client.findById(id).map { client =>
    Ok(views.html.Clients.display(client))
  }.getOrElse(NotFound)
}
GET   /clients              controllers.Clients.list(page: Int ?= 1)

函数的参数带默认值

GET   /api/list-all         controllers.Api.list(version: Option[String])

可选的参数

3.反向路由

package controllers
import javax.inject.Inject
import play.api._
import play.api.mvc._

class Application @Inject()(cc:ControllerComponents) extends AbstractController(cc)  {
  def hello(name: String) = Action {
    Ok("Hello " + name + "!")
  }
}

GET   /hello/:name          controllers.Application.hello(name)

def helloBob = Action {Redirect(routes.Application.hello("Bob"))}

4.相对路由

package controllers
import javax.inject._
import play.api.mvc._
@Singleton
class Relative @Inject()(cc: ControllerComponents) extends AbstractController(cc) {
  def helloview() = Action { implicit request =>
    Ok(views.html.hello("Bob"))
  }
  def hello(name: String) = Action {
    Ok(s"Hello $name!")
  }
}


GET     /foo/bar/hello              controllers.Relative.helloview
GET     /hello/:name                controllers.Relative.hello(name)


@(name: String)(implicit request: RequestHeader)
<h1>Hello @name</h1>
<a href="@routes.Relative.hello(name)">Absolute Link</a>
<a href="@routes.Relative.hello(name).relative">Relative Link</a>


<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Bob</title>
    </head>
    <body>
      <a href="/hello/Bob">Absolute Link</a>
      <a href="../../hello/Bob">Relative Link</a>
    </body>
</html>

5.一些默认的

# Redirects to https://www.playframework.com/ with 303 See Other
GET   /about      controllers.Default.redirect(to = "https://www.playframework.com/")

# Responds with 404 Not Found
GET   /orders     controllers.Default.notFound

# Responds with 500 Internal Server Error
GET   /clients    controllers.Default.error

# Responds with 501 Not Implemented
GET   /posts      controllers.Default.todo

猜你喜欢

转载自www.cnblogs.com/feiyumo/p/9126151.html