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

本文通过一个具体的Play框架示例,介绍了如何正确配置routes文件来实现应用中的路由映射,并解释了因配置缺失导致的错误及其解决方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先贴 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
再看看华丽的开发模式直接在浏览器端报错截图:
[img]http://dl2.iteye.com/upload/attachment/0094/9362/69236054-e7fe-3f75-b5c7-92635bf3bafd.png[/img]

后来用控制台编译的时候发现 还有个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还是很方便的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值