2

您好,我是 scala play 框架的初学者。我创建了一个简单的注册表单并连接到 mysql 以插入行。效果很好。现在我想在同一页面上显示那些插入的行,而不使用 json 刷新页面。请建议我如何在同一页面上获取插入的行。在此先感谢。这是我的以下代码

Routes:
# Home page
GET     / controllers.Application.index
GET     /createform                 controllers.StudentController.createform()
POST    /save                   controllers.StudentController.save()    

控制器:学生控制器

package controllers

import play.api.mvc._
import play.api.data._
import play.api.data.Forms._

import scala.collection.mutable.HashMap

import views.html
import models.Student

object StudentController extends Controller {


val studentform= Form (

tuple(
"firstname"->text,
"lastname"->text
    )
)
def createform = Action {

Ok(html.createform(studentform))

}

def save = Action { implicit request=>

studentform.bindFromRequest.fold(
errors=> BadRequest(html.createform(errors)),
{
    case(firstname,lastname)=>Student.create(firstname,lastname)
    Redirect(routes.Application.index())
}

    )

}

}

Application Controller

package controllers

import play.api._
import play.api.mvc._

object Application extends Controller {

  def index = Action {

    Redirect(routes.StudentController.createform)
    //Ok(views.html.index("Your new application is ready."))
  }

}

楷模:

封装模型

import play.api.db._
import play.api.Play.current

import anorm._
import anorm.SqlParser._

case class Student (

    id:Pk[Long]=NotAssigned,
    firstname: String,
    lastname: String

)


object Student {

def create(firstname: String,lastname:String) : Unit={

DB.withConnection{ implicit Connection=>

SQL("insert into student (Firstname,Lastname)" + "values({firstname},{lastname})"
).on(
'firstname->firstname,
'lastname->lastname
).executeUpdate()
    }

}

}

查看 createform.scala.html

@(studentform: Form[(String,String)])

@import helper._

@main(title="Student Registration Form"){

@form(action=routes.StudentController.save){

    <fieldset>
<legend>Add Student</legend>

@inputText(
field=studentform("firstname"),
args='_label->"FirstName"
)

@inputText(
field=studentform("lastname"),
args='_label->"LastName"
)
<br/>
<div class="actions">
<input type="submit" value="Submit">
<a href="@routes.Application.index">Cancel</a>
</div>

    </fieldset>


}

}

index.scala.html

@main("Welcome to Play 2.0") {

    <a href="/createform">Add a new Student</a>
}

请建议我将插入的数据存储在 JSON 对象中,并将相同的插入行存储在 scala 的同一页面上。提前致谢

4

1 回答 1

1

使用 json 读取和写入,然后将 student 作为对象传递给您的 create 方法:

object Student {

  implicit object PkFormat extends Format[Pk[Long]] {
    def reads(json: JsValue):JsResult[Pk[Long]] = JsSuccess(Id(json.as[Long]))
    def writes(id: Pk[Long]):JsNumber = JsNumber(id.get)
  }

  implicit val studentReads: Reads[Student] = (
    (__ \ "id").readNullable[Pk[Long]].map(_.getOrElse(NotAssigned)) ~
    (__ \ "firstname").read[String] ~
    (__ \ "lastname").read[String]
  )(Student.apply _)

  implicit val studentWrites = Json.writes[Student]

  def create(student: Student): Student = {
    DB.withConnection { implicit c =>

      val id: Long = student.id.getOrElse {
        SQL("select next value for student_id_seq").as(scalar[Long].single)
      }

      SQL(
        """
          insert into student values (
            {id}, {firstname}, {lastname}
          )
        """
      ).on(
        'id -> id,
        'firstname -> student.firstname
        'lastname -> student.lastname
      ).executeUpdate()

      student.copy(id = Id(id))
    }
  }

}

然后“同一页面”可以只是一个 ajax 提交的表单,将带有名字和姓氏的学生对象传递给 create 方法,然后重新渲染或附加到学生列表。您可以通过返回新添加的学生,然后附加结果,或者为整个学生列表再次调用数据库并呈现整个列表来将响应传回。

于 2013-06-04T05:59:49.637 回答