play frameworkを使ってみる

activatorをインストー

brew install typesafe-activator 

プロジェクトの作成

activator new myapp play-scala 

myappというディレクトリができました.

myappに移動して,sbt compileコンパイルsbt runで実行します.

http://localhost:9000/にアクセスすると,play frameworkの画面がでてきました.

とりあえずプロジェクト作成時に出てきたソースコードを見てみる.

conf/routes

# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~

# An example controller showing a sample home page
GET     /                           controllers.HomeController.index
# An example controller showing how to use dependency injection
GET     /count                      controllers.CountController.count
# An example controller showing how to write asynchronous code
GET     /message                    controllers.AsyncController.message

# Map static resources from the /public folder to the /assets URL path
GET     /assets/*file               controllers.Assets.versioned(path="/public", file: Asset)

requestMapping的な何かをしてそうなところ

HomeControllerを見てみる

package controllers

import javax.inject._
import play.api._
import play.api.mvc._

/**
 * This controller creates an `Action` to handle HTTP requests to the
 * application's home page.
 */
@Singleton
class HomeController @Inject() extends Controller {

  /**
   * Create an Action to render an HTML page with a welcome message.
   * The configuration in the `routes` file means that this method
   * will be called when the application receives a `GET` request with
   * a path of `/`.
   */
  def index = Action {
    Ok(views.html.index("Your new application is ready."))
  }
}

views/index.scala.htmlを返してそう

index.scala.htmlは同じところにあるmain.scala.htmlを読んでいるらしい

CountControllerを見てみる

package controllers

import javax.inject._
import play.api._
import play.api.mvc._

import services.Counter

/**
 * This controller demonstrates how to use dependency injection to
 * bind a component into a controller class. The class creates an
 * `Action` that shows an incrementing count to users. The [[Counter]]
 * object is injected by the Guice dependency injection system.
 */
@Singleton
class CountController @Inject() (counter: Counter) extends Controller {

  /**
   * Create an action that responds with the [[Counter]]'s current
   * count. The result is plain text. This `Action` is mapped to
   * `GET /count` requests by an entry in the `routes` config file.
   */
  def count = Action { Ok(counter.nextCount().toString) }

}

counter.nextCount()を呼んでそう

counterクラスを呼んでそう

Counter.scalaを見てみる

package services

import java.util.concurrent.atomic.AtomicInteger
import javax.inject._

/**
 * This trait demonstrates how to create a component that is injected
 * into a controller. The trait represents a counter that returns a
 * incremented number each time it is called.
 */
trait Counter {
  def nextCount(): Int
}

/**
 * This class is a concrete implementation of the [[Counter]] trait.
 * It is configured for Guice dependency injection in the [[Module]]
 * class.
 *
 * This class has a `Singleton` annotation because we need to make
 * sure we only use one counter per application. Without this
 * annotation we would get a new instance every time a [[Counter]] is
 * injected.
 */
@Singleton
class AtomicCounter extends Counter {  
  private val atomicCounter = new AtomicInteger()
  override def nextCount(): Int = atomicCounter.getAndIncrement()
}

トレイトを実装したAtomicCounterがあった

getAndIncrement()で1足した値を取得してるっぽい

返ってきたやつをtoStringして出力といった感じ

とりあえずコントローラーにメソッドを一つ追加してみる

conf/routesを変更

GET     /test                       controllers.TestController.test

TestControllerの追加

package controllers

import javax.inject.Inject

import play.api.mvc.{Action, Controller}

/**
  * Created by mituba on 2017/06/29.
  */
class TestController @Inject() extends Controller {
  def test = Action {
    Ok("hello")
  }
}

実行してhttp://localhost:9000/testにアクセスするとhelloという文字が出た

とりあえずリクエストパラメータをもらってみる

conf/routesの変更

GET     /params                     controllers.ParamController.getParam

ParamController.scalaの追加

package controllers

import javax.inject.Inject

import play.api.mvc.{Action, Controller}


/**
  * Created by mituba on 2017/06/29.
  */
class ParamController @Inject() extends Controller  {
  def getParam = Action { request =>
    val params : Map[String, Seq[String]] = request.queryString
    val message = params("message").head

    Ok(message)
  }
}

実行してhttp://localhost:9000/params?message=helloにアクセスすると,helloと表示された.

まとめ

後はJSONの送り合いとDB処理の実装について調べてみたい.