增加留言表

增加创建留言,获取留言接口,和客户端对接。
master
pan 3 years ago
parent 4076936680
commit 662c6930a0
  1. 4
      resources/application.conf
  2. 1
      src/Application.kt
  3. 47
      src/Controller.kt
  4. 26
      src/Dao.kt
  5. 2
      src/MySQL.kt
  6. 69
      src/Service.kt
  7. 17
      src/TestController.kt
  8. 22
      src/Vo.kt
  9. 9
      test/ApplicationTest.kt

@ -8,7 +8,9 @@ ktor {
jdbcUrl = "jdbc:mysql://localhost:3306/csams" jdbcUrl = "jdbc:mysql://localhost:3306/csams"
driverClassName = "com.mysql.cj.jdbc.Driver" driverClassName = "com.mysql.cj.jdbc.Driver"
} }
leaveMessage {
maxSize = 20
}
watch = [ classes ] watch = [ classes ]
} }
application { application {

@ -32,4 +32,5 @@ fun Application.module(testing: Boolean = false) {
fun Application.Controller(testing: Boolean = false){ fun Application.Controller(testing: Boolean = false){
this.AccountController() this.AccountController()
this.TestController() this.TestController()
this.MainController()
} }

@ -6,6 +6,15 @@ import io.ktor.response.*
import io.ktor.routing.* import io.ktor.routing.*
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
suspend inline fun <reified T:BaseVo> withToken(call:ApplicationCall, callback:(vo:T)->Unit){
val levelVo=call.receive<T>()
if(AccountService.validToken(levelVo.token)){
callback(levelVo)
}else{
call.respond(ApiResponse(message = "token校验失败",body = null))
}
}
private val logger = LoggerFactory.getLogger(Application::class.java) private val logger = LoggerFactory.getLogger(Application::class.java)
fun Application.AccountController() { fun Application.AccountController() {
@ -46,9 +55,9 @@ fun Application.AccountController() {
post{ post{
val userLoginVo= call.receive<UserLoginVo>() val userLoginVo= call.receive<UserLoginVo>()
logger.info("执行登陆") logger.info("执行登陆")
val tokenResDto:TokenResDto=AccountService.login(userLoginVo,call.request.host()) val token=AccountService.login(userLoginVo,call.request.host())
logger.info("登录请求处理完毕") logger.info("登录请求处理完毕")
call.respond(ApiResponse(message = if(tokenResDto.token!=null) "登陆成功" else "账号或密码错误!!!",body = tokenResDto)) call.respond(ApiResponse(message = if(token!=null) "登陆成功" else "账号或密码错误!!!",body = token))
} }
post(path = "/token"){ post(path = "/token"){
val tokenVo=call.receive<TokenVo>() val tokenVo=call.receive<TokenVo>()
@ -68,3 +77,37 @@ fun Application.AccountController() {
} }
} }
/**
* 主界面接口
*
*/
fun Application.MainController(){
MainService.register(maxSize = environment.config.property("ktor.deployment.leaveMessage.maxSize").getString().toInt())
routing {
//发送留言
route("$ApiPathPrefix/main") {
post("/leaveMessage") {
withToken<LeaveMessageVo>(call){
val flag=MainService.createMessage(leaveMessageVo = it)
call.respond(ApiResponse(message = if(flag) "留言创建成功" else "留言创建失败",body=flag))
}
}
post("/getMessage"){
withToken<OnlyToken>(call){
val s=MainService.getAllLeaveMessage()
call.respond(ApiResponse(message = "留言获取成功",body = s))
}
}
}
}
}
fun Application.TestController(){
routing {
get("$ApiPathPrefix/test"){
AccountService.test()
call.respond(ApiResponse(message = "成功连接服务端",body=true))
}
}
}

@ -5,6 +5,8 @@ import org.jetbrains.exposed.dao.IntEntityClass
import org.jetbrains.exposed.dao.id.EntityID import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.dao.id.IntIdTable import org.jetbrains.exposed.dao.id.IntIdTable
import org.jetbrains.exposed.sql.Column import org.jetbrains.exposed.sql.Column
import org.jetbrains.exposed.sql.`java-time`.CurrentDateTime
import org.jetbrains.exposed.sql.`java-time`.CurrentTimestamp
import org.jetbrains.exposed.sql.`java-time`.datetime import org.jetbrains.exposed.sql.`java-time`.datetime
import java.time.LocalDateTime import java.time.LocalDateTime
@ -41,7 +43,7 @@ object UserTokens: IntIdTable(){
val ip:Column<String> = varchar(name="ip",length = 32) val ip:Column<String> = varchar(name="ip",length = 32)
@TableComment("令牌创建时间") @TableComment("令牌创建时间")
val createTime:Column<LocalDateTime> = datetime("create_time").default(LocalDateTime.now()) val createTime:Column<LocalDateTime> = datetime("create_time").defaultExpression(CurrentTimestamp())
@TableComment("授权设备") @TableComment("授权设备")
val device:Column<String> = varchar(name="device",length = 256) val device:Column<String> = varchar(name="device",length = 256)
@ -54,4 +56,24 @@ class UserToken(id:EntityID<Int>):IntEntity(id){
var ip by UserTokens.ip var ip by UserTokens.ip
var createTime by UserTokens.createTime var createTime by UserTokens.createTime
var device by UserTokens.device var device by UserTokens.device
} }
@TableComment("留言")
object LeaveMessages:IntIdTable(){
@TableComment("留言用户")
val studentId:Column<String> = reference("student_id",Users.studentId)
@TableComment("留言内容")
val message:Column<String> = varchar(name = "message",length = 20)
@TableComment("留言创建时间")
val createTime:Column<LocalDateTime> = datetime("create_time").defaultExpression(CurrentDateTime())
}
class LeaveMessage(id:EntityID<Int>):IntEntity(id){
companion object:IntEntityClass<LeaveMessage>(LeaveMessages)
var studentId by LeaveMessages.studentId
var message by LeaveMessages.message
var createTime by LeaveMessages.createTime
}

@ -40,7 +40,7 @@ fun Application.MySQL(testing: Boolean = false){
fun initTable(){ fun initTable(){
transaction { transaction {
val tableList= arrayOf(Users,UserTokens) val tableList= arrayOf(Users,UserTokens,LeaveMessages)
SchemaUtils.createMissingTablesAndColumns(*tableList) SchemaUtils.createMissingTablesAndColumns(*tableList)
updateComment(*tableList) updateComment(*tableList)

@ -42,18 +42,18 @@ object AccountService {
* *
* @param userLoginVo 登陆表单 * @param userLoginVo 登陆表单
*/ */
fun login(userLoginVo: UserLoginVo,_ip:String):TokenResDto{ fun login(userLoginVo: UserLoginVo,_ip:String):Token?{
return transaction { return transaction {
val user=User.find { Users.studentId eq userLoginVo.studentId }.firstOrNull() val user=User.find { Users.studentId eq userLoginVo.studentId }.firstOrNull()
when { when {
user==null -> { user==null -> {
logger.warn("学号:${userLoginVo.studentId}不存在") logger.warn("学号:${userLoginVo.studentId}不存在")
return@transaction TokenResDto(isValid = false) return@transaction null
} }
userLoginVo.password.md5() != user.password -> { userLoginVo.password.md5() != user.password -> {
logger.warn("密码:${userLoginVo.password}错误") logger.warn("密码:${userLoginVo.password}错误")
return@transaction TokenResDto(isValid = false) return@transaction null
} }
else -> { else -> {
val token=UserToken.new{ val token=UserToken.new{
@ -62,13 +62,19 @@ object AccountService {
device=userLoginVo.device device=userLoginVo.device
token=listOf(studentId,ip,device).joinToString(separator = ('a' .. 'z').random().toString()).md5() token=listOf(studentId,ip,device).joinToString(separator = ('a' .. 'z').random().toString()).md5()
} }
return@transaction TokenResDto(isValid = true,token = Token(token = token.token,createTime = token.createTime.toEpochSecond( token.flush()
ZoneOffset.of("+8")),studentId = token.studentId)) return@transaction Token(studentId = userLoginVo.studentId,token = token.token,
createTime = token.createTime.toEpochSecond(
ZoneOffset.of("+8")),name=user.name)
} }
} }
} }
} }
fun validToken(token: Token):Boolean{
return validToken(TokenVo(token = token.token,studentId = token.studentId))
}
/** /**
* 令牌校验 * 令牌校验
* *
@ -98,4 +104,55 @@ object AccountService {
logger.info("结束测试") logger.info("结束测试")
} }
} }
object MainService{
private val logger = LoggerFactory.getLogger(MainService::class.java)
var maxSize:Int=20
fun register(maxSize:Int){
this.maxSize=maxSize
}
/**
* 创建留言信息
*
* @param leaveMessageVo
* @return
*/
fun createMessage(leaveMessageVo: LeaveMessageVo):Boolean{
return if(leaveMessageVo.message.isNotEmpty()){
return transaction {
val count=LeaveMessage.count().toInt()
logger.info("系统留言数:$count,限制数:$maxSize")
if(count>= maxSize){
LeaveMessage.all().sortedBy { it.createTime }.subList(0, count-maxSize).forEach {
it.delete()
}
}
logger.info("保存留言:${leaveMessageVo.message}")
LeaveMessage.new {
studentId = leaveMessageVo.token.studentId
message = leaveMessageVo.message
}
logger.info("留言保存成功")
return@transaction true
}
}else{
logger.info("留言不能为空")
false
}
}
fun getAllLeaveMessage():List<LeaveMessageFormatVo>{
return transaction {
logger.info("获取所有留言")
return@transaction LeaveMessage.all().toList().map {
LeaveMessageFormatVo(message = "${User.find { Users.studentId eq it.studentId }.first().name}说:${it.message}",studentId = it.studentId)
}
}
}
}

@ -1,17 +0,0 @@
package com.gyf.csams
import io.ktor.application.*
import io.ktor.response.*
import io.ktor.routing.*
import org.slf4j.LoggerFactory
private val logger = LoggerFactory.getLogger(Application::class.java)
fun Application.TestController(){
routing {
get("$ApiPathPrefix/test"){
AccountService.test()
call.respond(ApiResponse(message = "成功连接服务端",body=true))
}
}
}

@ -40,13 +40,17 @@ data class UserLogoutVo(val studentId:String)
data class UserResDto(val password:String) data class UserResDto(val password:String)
data class Token(val token:String,val createTime:Long,val studentId:String) data class Token(val token:String,val createTime:Long,val studentId:String,val name:String)
/**
* 令牌传输 data class TokenVo(val token:String,val studentId:String)
*
* @property isValid sealed class BaseVo{
* @property token abstract val token:Token
*/ }
data class TokenResDto(val isValid:Boolean,val token: Token?=null)
data class LeaveMessageVo(val message: String, override val token:Token):BaseVo()
data class OnlyToken(override val token: Token):BaseVo()
//data class PageVo(val pageSize:Int=10,val page:, override val token: Token):BaseVo()
data class TokenVo(val token:String,val studentId:String) data class LeaveMessageFormatVo(val message: String,val studentId: String)

@ -10,7 +10,6 @@ import io.ktor.config.*
import io.ktor.http.* import io.ktor.http.*
import io.ktor.server.testing.* import io.ktor.server.testing.*
import org.jetbrains.exposed.sql.transactions.transaction import org.jetbrains.exposed.sql.transactions.transaction
import java.time.LocalDateTime
import kotlin.test.Test import kotlin.test.Test
import kotlin.test.assertEquals import kotlin.test.assertEquals
@ -90,7 +89,13 @@ class ApplicationTest {
@Test @Test
fun localTime(){ fun localTime(){
println(LocalDateTime.now()) initApp {
transaction {
}
}
} }
/** /**

Loading…
Cancel
Save