play试用中由于某个找不到的方法的随想记录

先贴 play for scala 这本书中的教学例子:
def save = Action { implicit request =>
    val newProductForm = productForm.bindFromRequest()

    newProductForm.fold(
      hasErrors = { form =>
        Redirect(routes.Products.newProduct()).
          flashing(Flash(form.data) +
          ("error" -> Messages("validation.errors")))
      },
      success = { newProduct =>
        Product.add(newProduct)
        val message = Messages("products.new.success", newProduct.name)
        Redirect(routes.Products.show(newProduct.ean)).
          flashing("success" -> message)
      }
    )
  }


     一个名叫save 的 Action,是一个函数对象,就SpringMVC 里面Controller里面的一个方法是一个效果,大家可以看看play 试用起来比较优雅。
运行时:其中hasErrors 这个回调方法中的redirect 到 routes.Products.newProduct() 报错:value newProduct is not a member of controllers.ReverseProducts
再看看华丽的开发模式直接在浏览器端报错截图:


后来用控制台编译的时候发现 还有个routes.Products.save也是找不到
一开始还以为没有自动编译,后来准备放弃看下一章的时候,突然看到了routes 这个配置文件,
这里是出错时routes配置,REST风格(貌似和PHP配置很像,无意中见过同学的配置):
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~

# Home page
GET        /                     controllers.Application.index

GET        /products             controllers.Products.list

#GET        /products/new         controllers.Products.newProduct
GET        /products/:ean        controllers.Products.show(ean:Long)
GET        /barcode/:ean         controllers.Barcodes.barcode(ean: Long)

#POST       /products             controllers.Products.save

# Map static resources from the /public folder to the /assets URL path
GET        /assets/*file         controllers.Assets.at(path="/public", file)


我少了我注释的两个路径配置,于是明白了,这里play是通过 routes 这个配置文件生成的一些辅助的路由类,没有配置肯定就没有那些方法(属性),这也是为什么代码可以在Controller里面写成 routes.Products.newProduct()这种方法调用,这是scala ,静态类型语言,play框架是绕不过去这个检查的,这些东西都是类(Object),和我们自己写的一样,编译的时候play生成的。
生成的代码在:target/scala-2.10/src_managed/main/下面,当你看到这下面的代码结构基本就知道为什么了,本书第三章估计会讲这个过程,由于自己copy代码copy少了提前破解了其中的密码倒也比较开心。
对比下 servlet/jsp  play的编译方式更强大,连配置文件都帮你编译成了类,写代码看起来很像函数调用,其实都是函数调用,所以它在开发模式下有那么华丽的报错方式。
关于routes 这个配置文件 springmvc 如果也有一个就好了,其他方面springmvc还是很方便的

猜你喜欢

转载自roverll.iteye.com/blog/2031578