import io.vertx.ext.asyncsql.AsyncSQLClient import io.vertx.ext.asyncsql.MySQLClient val sqlClient = MySQLClient.createShared(vertx,JsonObject("host" to "localhost" ,"username" to "root" ,"password" to "root" ,"database" to "example"))
router.route("/login/:username/:password").handler{ if(it.session().get<String>("username")=="admin"){ it.response().end("{status:1,msg:\"You have logged in \"}") return@handler } val username = it.request().getParam("username") val password = it.request().getParam("password") sqlClient.querySingleWithParams("SELECT id,level FROM user WHERE username=? and password=?",JsonArray(username,password)){ if(it.failed() || it.result()==null){ it.response().end("{status:-1}") }else{ it.session().put("username",username) it.session().put("uid",it.result().getInteger(0)) it.session().put("level",it.result().getInteger(1)) it.response().end("{status:0}") } } }
//完整代码 import io.vertx.ext.web.Router import io.vertx.core.Vertx import io.vertx.ext.asyncsql.AsyncSQLClient import io.vertx.ext.asyncsql.MySQLClient //在本例中,sqlClient、vertx、router写在什么地方都无所谓。如果你用Java,请把他们放在他们应该在的地方 val sqlClient = MySQLClient.createShared(vertx,JsonObject("host" to "localhost" ,"username" to "root" ,"password" to "root" ,"database" to "example")) funmain(args:Array<String>){ val vertx = Vertx.vertx() val router = Router.router(vertx) val store = LocalSessionStore.create(vertx) router.route().handler(CookieHandler.create()) router.route().handler(SessionHandler.create(store)) router.route("/login/:username/:password").handler{ if(it.session().get<String>("username")=="admin"){ it.response().end("{status:1,msg:\"You have logged in \"}") return@handler } val username = it.request().getParam("username") val password = it.request().getParam("password") sqlClient.querySingleWithParams("SELECT id,level FROM user WHERE username=? and password=?",JsonArray(username,password)){ if(it.failed() || it.result()==null){ it.response().end("{status:-1}") }else{ it.session().put("username",username) it.session().put("uid",it.result().getInteger(0)) it.session().put("level",it.result().getInteger(1)) it.response().end("{status:0}") } } } vertx.createHttpServer().requestHandler{ router.accept(it) }.listen(80){ if(it.failed()) it.cause.printStackTrace() else println("Listening on 80") } }