开发框架

Play Framework

Play框架简介

img
  • Model-View-Controller (MVC) architecture
  • hot reloading:在接收请求时检查当前是否存在内容需要重新加载。

Play项目

sbt '-Dhttps.proxyHost=127.0.0.1' '-Dhttps.proxyPort=10809' new playframework/play-scala-seed.g8

将自动在当前目录下创建项目目录(目录名通过交互命令提供)。项目结构:


D:\USERS\GARY\ONEDRIVE\WORKSPACE\SCALA\LEARN-PLAY-FRAMEWORK
├─.g8
│  └─form
│      ├─app   # MVC
│      │  ├─controllers
│      │  └─views
│      └─test
│          └─controllers
├─app
│  ├─controllers
│  └─views
├─conf
├─project
├─public       # 静态资源
│  ├─images
│  ├─javascripts
│  └─stylesheets
└─test
    └─controllers

routes

conf/routes定义了URL的处理路径。

# An example controller showing a sample home page
GET  /              controllers.HomeController.index()
GET  /hello         controllers.HomeController.hello(name: String)
# Map static resources from the /public folder to the /assets URL path
GET  /assets/*file  controllers.Assets.versioned(path="/public", file: Asset)

MVC架构

使用MVC架构处理并响应URL。

视图及模板

app/views中定义了Web应用的视图,支持使用模板(Twirl+HTML)。

@(name:String)
@main("Hello") {
    <section id="top">
        <div class="wrapper">
            <h1>Hello World, @name!</h1>
        </div>
    </section>
}

Twirl模板语法:

  • @开始的内容通过模板引擎生成内容。

  • @(var:Type)定义从控制器调用页面时传入的参数,在模板中使用@var引用参数。

  • @main("Hello", assetsFinder)引用其他模板内容,并传入参数。

  • {}中的内容将被插入生成的HTMLbody

控制器

以下定义控制器app/controllers及其包含的URL处理方法。通过在routes文件中添加声明,以调用该控制器中的URL处理方法。

class HomeController extends BaseController {
  /* "/"根URL处理 */
  def index() = Action { implicit request: Request[AnyContent] =>
    Ok(views.html.index())  // 对应app/views目录下的页面
  }
  /* URL参数处理和传递至视图 */
  def hello(name:String) = Action {
    Ok(views.html.hello(name))
  }
}

示例教程

Play’s documentation shows the available features and how to use them, but the documentation will not show how to create an application from start to finish. This is where tutorials and examples come in. Tutorials and examples are useful for showing a single application at work, especially when it comes to integrating with other systems such as databases or Javascript frameworks.

Play Tutorials - 2.8.x (playframework.com)