您好,我是 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 的同一页面上。提前致谢