Playframework(11)Scala Project and First Example
Playframework(11)ScalaProjectandFirstExample
Maybe,Iwilltryemacsinthefuture,butthistime,stillIwilluseeclipse.
Projectcreation
>playnewtodolist
AndthistimeIchoosesimpleScalaapplication.
preparetheIDE
>cdtodolist
>playeclipsify
Thenwecanimportthisprojecttoeclipse.
Entertheplayconsoleandstartthewebcontainer
>play
play>run
Visithttp://localhost:9000tomakesureitisworking.
Overview
ConfigurationisalmostthesameasJava.Sothereisnocommentshere.
Developmentworkflow
ChangetheApplication.scalatosimplecontent.
objectApplicationextendsController{
defindex=Action{
Ok("HelloSillycat!")
}
}
Preparingtheapplication
DidthesamethingsasinJavaProject,configuretheroutesfilefirst.
AndmakethecontrolTODOfirst.
deftasks=TODO
defnewTask=TODO
defdeleteTask(id:Long)=TODO
PreparetheTaskmodel
Firstlycreatethepackagemodelsunderapp.
ThecreateascalaclassTask.scalawithScalaWizards--->ScalaObject
Thecontentareasfollow,tillnow,theScalalanguagelooksbetterthanJava.
packagemodels
caseclassTask(id:Long,label:String)
objectTask{
defall():List[Task]=Nil
defcreate(label:String){}
defdelete(id:Long){}
}
Theapplicationtemplate
Modifytheindex.scala.htmltemplatefortasklistandformjustlikeinJavaproject.
ThetemplateengineisdesignedbyScala,itseemsworkingwithScalabackendismuchbetterthanwithJava.
@(tasks:List[Task],taskForm:Form[String])
@importhelper._
@main("TodoList"){
<h1]]>@tasks.sizetask(s)</h1]]>
<ul]]>
@tasks.map{task=>
<li]]>
@task.label
@form(routes.Application.deleteTask(task.id)){
<inputtype="submit"value="Delete"]]>
}
</li]]>
}
</ul]]>
<h2]]>Addanewtask</h2]]>
@form(routes.Application.newTask){
@inputText(taskForm("label"))
<inputtype="submit"value="Create"]]>
}
}
Thetaskform
AFormobjectencapsulatesanHTMLFormdefinition,includingvalidationconstraints.
importplay.api.data._
importplay.api.mvc._
importplay.api.data.Forms._
valtaskForm=Form(
"label"->nonEmptyText
)
Renderingthefirstpage
Iimplementtheactiontaskslikethis:
deftasks=Action{
Ok(views.html.index(Task.all(),taskForm))
}
butIgot
ErrorMessage:
toomanyargumentsformethodapply
Solution:
Rightnow,itseemright,buteclipsedidnotawareofthat.Ihavenosolution.IalreadyhaveScalapluginsinmyclass.
Oops,IfindthepropertiesoftheprojectandchoosetheScalaCompileranduncheckthe[UseProjectSettings]
Handlingtheformsubmission
HandleandimplementthenewTaskaction
defnewTask=Action{implicitrequest=>
taskForm.bindFromRequest.fold(
errors=>BadRequest(views.html.index(Task.all(),errors)),
label=>{
Task.create(label)
Redirect(routes.Application.tasks)
})
}
Persistthetasksinadatabase
Changethedatabaseconfigurationinconf/application.confaccordingtotheJavaProject.
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"
ThedifferencesarethatweneedtocreatetheSQLtableforthat.
createthefileconf/evolutions/default/1.sql
#Tasksschema
#----!Ups
CREATESEQUENCEtask_id_seq;
CREATETABLEtask(
idintegerNOTNULLDEFAULTnextval('task_id_seq'),
labelvarchar(255)
);
#---!Downs
DROPTABLEtask;
DROPSEQUENCEtask_id_seq;
AfterIcreatetheSQLs,Irefreshthepage.Playtellmeweneedevolution.IclickonApplythisscript.Itisreallymagic.
NextstepistoimplementtheSQLqueries.DefinetheusingofAnormfirst
importanorm._
importanorm.SqlParser._
valtask={
get[Long]("id")~
get[String]("label")map{
caseid~label=>Task(id,label)
}
}
importplay.api.db._
importplay.api.Play.current
defall():List[Task]=DB.withConnection{implicitc=>
SQL("select*fromtask").as(task*)
}
Payattentiontotheimportstatements,sometimes,eclipsecannotimportthatforyou.
defcreate(label:String){
DB.withConnection{implicitc=>
SQL("insertintotask(label)values({label})").on(
'label->label
).executeUpdate()
}
}
defdelete(id:Long){
DB.withConnection{implicitc=>
SQL("deletefromtaskwhereid={id}").on(
'id->id
).executeUpdate()
}
}
AddingtheDeletingTasks
defdeleteTask(id:Long)=Action{
Task.delete(id)
Redirect(routes.Application.tasks())
}
Itisthere,itisdone.Totallyspeaking,Ifeelplayframeworkisreallygreat,anditisworthingspeedtimeonScala.Itisreallyamagiclanguage.
Spring,JavaandalotofrelatedJ2EEframework,theyaremyoldloversnow.
References:
http://www.playframework.org/documentation/2.0.4/ScalaTodoList