上周我刚刚发现了带有 Play 2 框架的 Scala 语言,我有点困惑..
我尝试使用本教程制作一个带有用户名和密码的简单表单:
但是在控制器中我有一个不起作用的功能:
def addUser() = Action { implicit request =>
userForm.bindFromRequest.fold(
errors => BadRequest,
{
case (username) =>
User.create(User(NotAssigned, username, password))
Redirect(routes.Application.index())
}
)
}
它返回:未找到:值密码
如果我把密码放在盒子里,它也不会起作用..
任何的想法 ?
应用程序.scala:
package controllers
import play.api._
import play.api.mvc._
import play.api.data.Form
import play.api.data.Forms.{single, nonEmptyText}
import play.api.mvc.{Action, Controller}
import anorm.NotAssigned
import models.User
object Application extends Controller {
val userForm = Form {
tuple(
"username" -> nonEmptyText,
"password" -> nonEmptyText
)
}
def index = Action {
Ok(views.html.index(userForm))
}
def addUser() = Action { implicit request =>
userForm.bindFromRequest.fold(
errors => BadRequest,
{
case (username, password) =>
User.create(User(NotAssigned, username, password))
Redirect(routes.Application.index())
}
)
}
}
用户.scala:
package models
import play.api.db._
import play.api.Play.current
import anorm._
import anorm.SqlParser._
case class User(id: Pk[Long], username: String, password: String)
object User {
val simple = {
get[Pk[Long]]("id") ~
get[String]("username") ~
get[String]("password") map {
case username~password => User(id, username)
case id~username => User(id, username)
}
}
def findAll(): Seq[User] = {
DB.withConnection { implicit connection =>
SQL("SELECT * FROM user").as(User.simple *)
}
}
def create(user: User): Unit = {
DB.withConnection { implicit connection =>
SQL("INSERT INTO user(username, password) VALUES ({username}, {password})").on(
'username -> user.username ,
'password -> user.password
).executeUpdate()
}
}
}