To make the page work, we'll define a combination of the following: 1. A view template (A template that generates HTML) 2. A controller action (A Scala function the renders the view) 3. Route configuration (Configuration to map the URL to the action) 4. The model (Scala code the defines the data structure and some test data)

大概的流程如图所示(其实,控制器是最核心的,它使用了View Template和Model所提供的接口) enter image description here

第一步:使用Play命令创建新的项目 这个时候系统会让你在四个模板中间选择一个 enter image description here 进入项目的主目录 cd products 运行项目 play run

第二步:Stylesheets 将bootstrap.css拷贝到public/stylesheets目录中,这样我们的template就可以连接到该文件了。同时将glyphicons-halflings-whitepng和glyphicons-halflings.png拷贝至public/img目录中。本项目也会用到自定义的css以覆盖bootstrap的设置,这个css的名字即为main.css(参见Listing2.1)

第三步:添加Model A model class ( The definition of the product and its attributes) A data access object (DAO, code that provides access to product data) Test data (A set of product objects) 这些东西使用一个带Object部分的case class就可以全部解决了

第四步:Product list pages 把这个文件放在views.html.products包中。

@(products: List[Product]) (implicit lang:Lang)

    <dl class="products">
          @for(product <- products){

This is a Scala template: an HTML document with embedded Scala statements, which start with an @character. 而该生成的HTML块可以作为参数传递给另一个模块,即main。

第五步:Layout template

@(title: String)(content: Html)(implicit lang: Lang)
<!DOCTYPE html>
  <link rel="stylesheet" type="text/css" media="screen"
  <link rel="stylesheet" media="screen"
<div class="screenshot">
  <div class="navbar navbar-fixed-top">
    <div class="navbar-inner">
<a class="brand" href="@routes.Application.index()">
</a> </div>
  <div class="container">

The main purpose of this template is to provide a reusable structure for HTML pages in the application, with a common layout.

第六步:Controller action method


package controllers
import play.api.mvc.{Action, Controller}
import models.Product
object Products extends Controller {
  def list = Action { implicit request =>
    val products = Product.findAll

第七步:Adding a routes configuration The routes configuration specifies the mapping from HTTP to the Scala code in our controllers.we need to map the /products URL to the controllers.Products.list action. This means adding a new line in the conf/routes file.

GET /  controllers.Application.index
GET /products  controllers.Products.list
GET /assets/*file"/public", file)

第八步:Replacing the welcome page with a redirect You can replace it with an HTTP redirect to the products list by changing the controller action in app/controllers/Application.scala to return an HTTP redirect response instead of rendering the default template.

package controllers
import play.api.mvc.{Action, Controller}
object Application extends Controller {
  def index = Action {
} }

Detail Page 第一步:Adding a parameter to a controller action