SmartWeb 快速开始
本页用 SmartHTTP 服务器搭一个最小 HTTP 服务:一个 Controller、两个接口,然后用 curl 访问。
添加依赖
kotlin
plugins {
kotlin("jvm") version "2.3.0"
application
}
repositories {
mavenCentral()
maven("https://maven.cnb.cool/IceCream/maven/-/packages/")
}
dependencies {
implementation("com.IceCreamQAQ.Rain:application:1.0.0-DEV14")
implementation("com.IceCreamQAQ.Rain:controller:1.0.0-DEV14")
implementation("com.IceCreamQAQ.SmartWeb:SmartWeb:1.0.0-DEV15")
implementation("com.IceCreamQAQ.SmartWeb.Server:SmartHTTP:1.0.0-DEV15")
}
application {
mainClass.set("com.example.MainKt")
}SmartWeb 只在运行时依赖 Rain,不会把 Rain 带到编译期,所以要自己声明 Rain 依赖:application 提供启动器,controller 提供 @Path、@Before 等注解。服务器模块会登记自己为默认服务器实现,引入一个即可。
创建入口
kotlin
package com.example
import rain.application.FullStackApplicationLauncher
fun main() {
FullStackApplicationLauncher.launch()
}Java 项目请使用 FullStackApplicationLauncher。它通过 Rain 的类加载器加载 Controller,加载时会为 Java 方法参数补上参数名,详见参数名。
创建控制器
kotlin
package com.example
import rain.controller.annotation.Path
import smartweb.annotation.GetAction
import smartweb.annotation.PostAction
import smartweb.annotation.WebController
@WebController
@Path("users")
class UserController {
@GetAction("{id}")
fun getUser(id: Long) = mapOf("id" to id)
@PostAction
fun createUser(name: String) = mapOf("name" to name)
}@Path 设置控制器的路径前缀,Action 注解设置相对路径。路径里的 {id} 按名字绑定到方法参数 id。
添加配置
创建 src/main/resources/conf/application.properties:
properties
rain.scanPackages=com.example
webServer.port=8080webServer.port 是必填项,缺少时启动会报错。
运行
启动应用后访问:
bash
curl http://localhost:8080/users/1
# {"id":1}
curl -X POST -d 'name=alice' http://localhost:8080/users
# {"name":"alice"}
curl -X POST -H 'Content-Type: application/json' -d '{"name":"alice"}' http://localhost:8080/users
# {"name":"alice"}最后一个请求说明了 SmartWeb 的一个特点:JSON 对象的字段会合并进请求参数,简单类型参数可以直接从 JSON 请求体取值。