接收表格参数到Ktor服务器

时间:2017-09-23 21:28:32

标签: kotlin ktor

我是Java和Kotlin的新手,尝试使用Ktor构建联系表单,因此我启用了here的gmail不安全连接,并在下面构建了应用程序:

blogApp.kt

package blog

import org.jetbrains.ktor.netty.*
import org.jetbrains.ktor.routing.*
import org.jetbrains.ktor.application.*
import org.jetbrains.ktor.features.*
import org.jetbrains.ktor.host.*
import org.jetbrains.ktor.http.*
import org.jetbrains.ktor.response.*

import org.apache.commons.mail.*

fun Application.module() {
    install(DefaultHeaders)
    install(CallLogging)
    install(Routing) {
        get("/") {
            call.respondText("""
            My Example Blog2
                <form action="/contact-us" method="post">
                    <input name="subject" placeholder="Subject">
                    <br>
                    <textarea name="message" placeholder="Your message ..."></textarea>
                    <br>
                    <button>Submit</button>
                </form>
            """, ContentType.Text.Html)
        }
        post("/contact-us") {
            SimpleEmail().apply {
                setHostName("smtp.gmail.com")
                setSmtpPort(465)
                setAuthenticator(DefaultAuthenticator("my_alias@gmail.com", "my_gmil_passoword"))
                setSSLOnConnect(true)
                setFrom("my_alias@gmail.com")
                setSubject("subject")        // I need to use formParam
                setMsg("message")            // I need to use formParam
                addTo("my_alias@gmail.com")
            }.send() // will throw email-exception if something is wrong
            call.respondRedirect("/contact-us/success")
        }
        get("/contact-us/success") { 
            call.respondText("Your message was sent", ContentType.Text.Html) 
        }
    }
}

fun main(args: Array<String>) {
    embeddedServer(Netty, 8080, watchPaths = listOf("BlogAppKt"), module = Application::module).start()
}

build.gradle

group 'Example'

version 'alpha'

buildscript {
    ext.kotlin_version = '1.1.4-3'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

apply plugin: 'java'
apply plugin: 'kotlin'

sourceCompatibility = 1.8
ext.ktor_version = '0.4.0'

repositories {
    mavenCentral()
    maven { url  "http://dl.bintray.com/kotlin/ktor" }
    maven { url "https://dl.bintray.com/kotlin/kotlinx" }
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
    compile "org.jetbrains.ktor:ktor-core:$ktor_version"
    compile "org.jetbrains.ktor:ktor-netty:$ktor_version"
    compile "org.apache.commons:commons-email:1.4"
    compile "org.slf4j:slf4j-simple:1.7.25"
    compile "ch.qos.logback:logback-classic:1.2.1"
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
kotlin {
    experimental {
        coroutines "enable"
    }
}


jar {
    baseName 'abc'
    manifest {
        attributes 'Main-Class': 'blog.BlogAppKt'
    }

    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}

随着事情顺利进行,我能够向自己发送电子邮件然后重定向到成功页面,但发送的消息是预先设置的数据:

        setSubject("subject")        // I need to use formParam
        setMsg("message")            // I need to use formParam

如何让Ktor接收用户真正在表单中输入的数据,如何阅读表格参数?

2 个答案:

答案 0 :(得分:6)

您可以使用call.receive<ValuesMap>()并内省数据:

import org.jetbrains.ktor.request.*     // for recieve
import org.jetbrains.ktor.util.*       // for ValuesMap

        post("/contact-us") {
            val post = call.receive<ValuesMap>() 
            val subj = post["subject"]
            val msg  = post["message"]

            SimpleEmail().apply { ... }
        }

注意:ValuesMap在最新的ktor版本中已弃用,因此请使用以下代码:

 val post = call.receiveParameters()

答案 1 :(得分:0)

虽然上面的答案在那个时候是正确的,但是今天当我通过kotlin + Ktor时,我看到上面的答案不再有效。

您现在需要的是这样的

  • call.receive <参数>()[“ PARAM_NAME”]

Parameters类在以下软件包中:io.ktor.http.Parameters

尼基尔