`
sillycat
  • 浏览: 2551828 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Playframework(11)Scala Project and First Example

 
阅读更多
Playframework(11)Scala Project and First Example
Maybe, I will try emacs in the future, but this time, still I will use eclipse.

Project creation
>play new todolist

And this time I choose simple Scala application.

prepare the IDE
>cd todolist
>play eclipsify

Then we can import this project to eclipse.
Enter the play console and start the web container
>play
play>run

Visit http://localhost:9000 to make sure it is working.

Overview
Configuration is almost the same as Java. So there is no comments here.

Development workflow
Change the Application.scala to simple content.

object Application extends Controller{
     def index = Action {
          Ok("Hello Sillycat!")
     }
}

Preparing the application
Did the same things as in Java Project, configure the routes file first.

And make the control TODO first.

def tasks = TODO
def newTask = TODO
def deleteTask(id: Long) = TODO

Prepare the Task model
Firstly create the package models under app.

The create a scala class Task.scala with Scala Wizards ---> Scala Object

The content are as follow, till now, the Scala language looks better than Java.
package models

case class Task(id: Long, label: String)

object Task {
 
  def all() : List[Task] = Nil
 
  def create(label: String) {}
 
  def delete(id: Long) {}

}

The application template
Modify the index.scala.html template for task list and form just like in Java project.

The template engine is designed by Scala, it seems working with Scala backend is much better than with Java.
@(tasks: List[Task], taskForm: Form[String])

@import helper._

@main("Todo List") {
<h1]]>@tasks.size task(s)</h1]]>
<ul]]>
@tasks.map { task =>
  <li]]>
@task.label

@form(routes.Application.deleteTask(task.id)){
  <inputtype="submit"value="Delete"]]>
}
  </li]]>
}
</ul]]>

<h2]]>Add a new task</h2]]>

@form(routes.Application.newTask){
  @inputText(taskForm("label"))
  <inputtype="submit"value="Create"]]>
}
 
}

The task form
A Form object encapsulates an HTML Form definition, including validation constraints.

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

val taskForm = Form(
     "label" -> nonEmptyText
)

Rendering the first page
I implement the action tasks like this:
  def tasks = Action {
    Ok(views.html.index(Task.all(), taskForm))
  }

but I got
Error Message:
too many arguments for method apply

Solution:
Right now, it seem right, but eclipse did not aware of that. I have no solution. I already have Scala plugins in my class.

Oops, I find the properties of the project and choose the Scala Compiler and uncheck the [Use Project Settings]

Handling the form submission
Handle and implement the newTask action
  def newTask = Action { implicit request =>
    taskForm.bindFromRequest.fold(
      errors => BadRequest(views.html.index(Task.all(), errors)),
      label => {
        Task.create(label)
        Redirect(routes.Application.tasks)
      })
  }

Persist the tasks in a database
Change the database configuration in conf/application.conf according to the Java Project.
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"

The differences are that we need to create the SQL table for that.
create the file conf/evolutions/default/1.sql
#Tasks schema

# ----!Ups
CREATE SEQUENCE task_id_seq;
CREATETABLE task (
id integerNOTNULLDEFAULT nextval('task_id_seq'),
label varchar(255)
);

# --- !Downs
DROPTABLE task;
DROP SEQUENCE task_id_seq;

After I create the SQLs, I refresh the page. Play tell me we need evolution. I click on Apply this script. It is really magic.

Next step is to implement the SQL queries. Define the using of Anorm first

 
import anorm._
import anorm.SqlParser._

    val task = {

    get[Long]("id") ~
    get[String]("label") map{
      case id~label => Task(id, label)
    }
  }

import play.api.db._
import play.api.Play.current
  def all() : List[Task] = DB.withConnection { implicit c =>
    SQL("select * from task").as(task *)
  }

Pay attention to the import statements, sometimes, eclipse can not import that for you.
  def create(label: String) {
    DB.withConnection{ implicit c =>
         SQL("insert into task (label) values ( {label} ) ").on(
              'label -> label
         ).executeUpdate()
    }
  }
 
  def delete(id: Long) {
    DB.withConnection { implicit c =>
    SQL("delete from task where id = {id}").on(
    'id -> id
    ).executeUpdate()
    }
  }

Adding the Deleting Tasks
  def deleteTask(id: Long) = Action {
    Task.delete(id)
    Redirect(routes.Application.tasks())
  }

It is there, it is done. Totally speaking, I feel play framework is really great, and it is worthing speed time on Scala. It is really a magic language.

Spring, Java and a lot of related J2EE framework, they are my old lovers now.

References:
http://www.playframework.org/documentation/2.0.4/ScalaTodoList


分享到:
评论

相关推荐

    Mastering Play Framework for Scala

    Mastering Play Framework for Scala

    Mastering Play Framework for Scala.pdf

    Leverage the awesome features of Play Framework to build scalable, resilient, and responsive applications First published: May 2015 274page

    Mastering Play Framework for Scala 无水印pdf 0分

    Mastering Play Framework for Scala 英文无水印pdf pdf使用FoxitReader和PDF-XChangeViewer测试可以打开

    Mastering Play Framework for Scala mobi

    Mastering Play Framework for Scala 英文mobi 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

    Mastering Play Framework for Scala epub

    Mastering Play Framework for Scala 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

    mastering play framework for scala

    《精通Scala的Play框架》是一本专为Scala开发者设计的深度学习指南,旨在帮助读者全面理解和熟练运用Play框架。Play框架是构建Web应用程序的一个强大工具,尤其在Scala语言的支持下,它提供了高度的灵活性和效率。这...

    《mastering play framework for scala》 Shiti Saxena & 著

    This book is intended for those developers who are keen to master the internal workings of Play Framework to effectively build and deploy web-related apps.

    PlayFramework框架安全模块.pdf

    Play Framework 是一个基于Java和Scala的高性能Web应用框架,它提供了快速开发、可测试和敏捷迭代的能力。在Play Framework中,安全模块是一个重要的组件,它帮助开发者实现基本的认证(Authentication)和授权...

    Play for Scala.pdf_several7zb_scala_play_play开发scalaweb_

    Play Framework是一種用Scala編寫的Web應用框架,其遵循模型-視圖-控制器建築模式。Play Framework使用Scala編寫,並可以被編譯成Java虛擬機器位元組碼中的其他編程語言使用;例如Java語言。

    Play Framework Cookbook.pdf

    - **框架简介**:Play Framework 是一个开源的 Web 开发框架,基于 Java 和 Scala 编程语言。它采用轻量级、非阻塞的服务端架构,特别适合开发高性能、可扩展的应用程序。Play Framework 通过其独特的设计理念简化了...

    scala学习-project.zip

    11. ** Scalactic和ScalaTest**:Scala社区广泛使用的测试库,帮助开发者编写单元测试和集成测试,确保代码质量。 12. **Scaladoc**:Scala的文档生成工具,类似于Java的Javadoc,用于自动生成API文档。 在这个...

    playframework中文教程.zip

    Play Framework 是一个开源的Web应用框架,主要针对Java和Scala开发者设计,它的核心理念是简化开发流程,提高开发效率,并且特别强调了RESTful架构风格。这个“playframework中文教程.zip”压缩包很可能是为了帮助...

    ddd-playframework-scala:Play框架的DDD示例(域驱动设计)

    Play Framework DDD示例Play框架的DDD示例播放框架:2.6.x Scala(Scala):2.12.6用例文章:创建并显示文章详细信息帐户:创建帐户并登录draw.io上的设计域:/ designs 给我一颗星星 :glowing_star: 如果你喜欢他们...

    play framework api,play! framework api,play api

    Play Framework 是一个开源的Web应用框架,用于构建现代、高性能的Java和Scala应用程序。它采用模型-视图-控制器(MVC)架构模式,并且强调简洁的代码和开发的即时反馈。Play Framework API 是开发者使用该框架进行...

    play-scala-forms-example:示例Play项目,显示表单处理

    总的来说,`play-scala-forms-example`项目为我们提供了一个很好的学习平台,展示了如何在Play Framework中使用Scala处理表单,包括表单定义、数据绑定、验证、重定向等关键环节。通过这个例子,开发者可以更好地...

    play-scala-slick-example:示例使用Slick播放Scala项目

    总结,`play-scala-slick-example`项目展示了如何利用Play Framework的高效特性,配合Scala Slick的类型安全数据库查询,构建健壮且易维护的Web应用程序。这样的组合为开发者提供了强大的工具,可以在Scala环境中...

    play-scala-streaming-example:示例Play应用程序,显示Scala中的Comet和Server Sent事件

    在这个特定的示例`play-scala-streaming-example`中,我们将探讨如何在Scala中使用Play Framework实现Comet技术和Server Sent Events(SSE)。 **Comet技术** Comet是一种用于实现实时Web通信的技术,它通过长时间...

    play-scala-tls-example:使用HTTPS和WS以及可选客户端身份验证的Play应用程序

    "example-app"和"example-project"标签表明这是一个教学性质的项目,适合初学者学习和理解Play Framework的安全特性。 `play-scala-tls-example-2.7.x`这个文件名可能指的是项目的源代码版本,其中的"2.7.x"表示...

Global site tag (gtag.js) - Google Analytics