LoginSignup
3
4

More than 5 years have passed since last update.

kotlinでSpark Frameworkを使ってみた

Posted at

kotlinでSpark Frameworkを使って簡単な実装をしてみた

Spark Frameworkについて

Spark FrameworkとはJavaで実装された軽量フレームワークことです。
Spark FrameworkではWebフレームワークやREST APIを作ることができます。
また標準でJava8のLambdaに対応しています。

実行環境

IntelliJ IDEA Version: 2017.2.5
Windows 10 Home

実装手順

1.IntelliJ IDEAでGradle projectを作成

2.できたbuild.gradleに次の一文を追記する

compile 'com.sparkjava:spark-core:2.6.0'

3.kotlinのprojectがない場合は作成する

コード

Hello.kt
import spark.Spark.*

object HelloWorld {
    @JvmStatic
    fun main(args: Array<String>)  {
        staticFileLocation("D:/kotlin/sample/src/main/kotlin")
        setPort(1111)

        get("/hello") { request, response ->
            "<h1>Hello Spark!!</h1>+<h2>test</h2>"
        }
        get("/db") { req, res ->
            val name = contro().get(0)
            """
            <h1>$name</h1>
            """
        }

    }

}
Controler.kt
class contro() : UserDao() {
    fun get(i : Int): User? {
        val id: Int = i
        return findById(id)
    }
}

User.kt
import java.util.concurrent.atomic.AtomicInteger

open class UserDao {
    val users = hashMapOf(
            0 to User(name = "Alice", email = "alice@alice.kt", id = 0),
            1 to User(name = "Bob", email = "bob@bob.kt", id = 1),
            2 to User(name = "Carol", email = "carol@carol.kt", id = 2),
            3 to User(name = "Dave", email = "dave@dave.kt", id = 3)
    )
    var lastId: AtomicInteger = AtomicInteger(users.size - 1)

    fun save(name: String, email: String) {
        val id = lastId.incrementAndGet()
        users.put(id, User(name = name, email = email, id = id))
    }
    fun findById(id: Int): User? {
        return users[id]
    }
    fun findByEmail(email: String): User? {
        return users.values.find { it.email == email }
    }
    fun update(id: Int, name: String, email: String) {
        users.put(id, User(name = name, email = email, id = id))
    }
    fun delete(id: Int) {
        users.remove(id)
    }
}
data class User(val name: String, val email: String, val id: Int)

実行結果

http://localhost:1111/hello
スクリーンショット (183).png

http://localhost:1111/db
スクリーンショット (182).png

動的にもできるしSQL2oを使うことでSQLもつかえるらしい

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4