KotlinSpring-405响应

pgky5nke  于 2023-01-12  发布在  Spring
关注(0)|答案(1)|浏览(93)

我正在尝试通过该教程:https://kotlinlang.org/docs/jvm-spring-boot-add-db-support.html#add-messages-to-database-via-http-request
当我发送后请求时,我得到:

{
    "timestamp": "2023-01-09T05:35:30.982+00:00",
    "status": 405,
    "error": "Method Not Allowed",
    "path": "/"
}

我的代码:

@SpringBootApplication
class DemoApplication

fun main(args: Array<String>) {
    runApplication<DemoApplication>(*args)
}

@RestController
class MessageController(val service: MessageService) {
    @GetMapping("/")
    fun index(): List<Message> = service.findMessages()

    @PostMapping()
    fun post(@RequestBody message: Message) {
        service.save(message)
    }
}

data class Message(val id: String?, val text: String)

@Service
class MessageService(val db: JdbcTemplate) {
    fun findMessages(): List<Message> = db.query("select * from messages") { response, _ ->
        Message(response.getString("id"), response.getString("text"))
    }

    fun save(message: Message){
        val id = message.id ?: UUID.randomUUID().toString()
        db.update("insert into messages values ( ?, ? )",
            id, message.text)
    }
}

我的要求:

POST http://localhost:8080/
Content-Type: application/json

{
  "text": "Hello!"
}
ndasle7k

ndasle7k1#

@PostMapping()注解中缺少路径-请查看@GetMapping("/")中的路径

相关问题