Skip to content

响应与渲染 ​

Action 的返回值由 InternalWebServer.buildResult 写成 HTTP 响应。最常见的情况是返回一个对象,SmartWeb 用 FastJSON2 序列化为 application/json:

kotlin
@GetAction("{id}")
fun user(id: Long): UserDto = userService.get(id)

返回值如何处理 ​

buildResult 按以下顺序判断:

  1. 结果是 Render:调用它,返回非 null 时用返回值重新走一遍本流程。
  2. Action 找到了模板且请求 Accept 首项为 text/html:渲染模板。当前版本这一步不会生效,见模板引擎。
  3. 结果为 null 且状态码仍是 200:POST 返回 201,其他方法返回 204,响应体为空。
  4. 按结果类型分派,见下表。
结果类型响应
String按开头猜测类型:{ 或 [ 为 application/json,<?xml 为 application/xml,< 为 text/html,其他为 text/plain
Byte、ByteArray原样写出,不设置 Content-Type
InputStream原样写出,写完后关闭
File、UploadFile按扩展名推断 Content-Type
DownloadFile使用指定的文件名、Content-Type 和长度,总是带 Content-Disposition
其他对象JSON 序列化,application/json

String 的类型猜测只是启发式规则。需要稳定的媒体类型时,返回 Render 并自己设置 Content-Type。

空返回值 ​

返回 null 或无返回值的 Action:

  • 状态码仍为 200 时,POST 返回 201,其他方法返回 204。只有在 Content-Length 还没有设置时,SmartWeb 才把它设为 0。
  • 状态码已被改成其他值时,不会进入上面的分支,而是按“其他对象”处理,响应体是 JSON 文本 null。

需要 404、带 Location 的 201 这类语义时,用 Render 明确写出。

文件与下载 ​

kotlin
@GetAction("report")
fun report(): DownloadFile = DownloadFile("report.csv", "text/csv", reportService.open(), reportService.size())

@GetAction("logo")
fun logo(): File = File("static/logo.png")

File 和 UploadFile 能识别的扩展名只有 png、gif、jpg、jpeg、mp3、mp4、js、css、html、txt。其他扩展名使用 application/octet-stream,并添加 Content-Disposition: filename="..."。文件名会原样写入 Header,来自用户输入时要先过滤换行和引号。

设置状态码与 Header ​

注入 Response 修改状态码、Header 和 Cookie,响应体仍通过返回值交给 SmartWeb:

kotlin
@PostAction("jobs")
fun submit(response: Response): JobAccepted {
    val job = jobService.submit()
    response.status = 202
    response.addHeader("Location", "/jobs/${job.id}")
    response.addCookie("lastJob", job.id.toString())
    return JobAccepted(job.id)
}

不要在 Action 中调用 response.write(...) 自己写响应体。Action 返回后 SmartWeb 仍会按返回值继续处理,可能再写一次状态和 Header,或追加一段 null。需要完全控制输出时使用 Render。

Render ​

Render 是自定义渲染的出口:

kotlin
fun interface Render {
    operator fun invoke(context: WebActionContext, server: InternalWebServer): Any?
    fun render(): Nothing = throw ActionResult(this)
}
  • invoke 返回非 null:返回值重新进入 buildResult,可以继续使用 JSON、String、File 等分派。
  • invoke 返回 null:SmartWeb 只调用一次 resp.write() 提交状态码和 Header,不写响应体。
  • 调用 render():抛出 ActionResult,立即结束当前过程链,并把这个 Render 作为结果。可以在 Before、Action 和 Catch 中使用。
kotlin
fun accepted(body: Any) = Render { context, _ ->
    context.resp.status = 202
    body
}

@Before
fun requireLogin(user: IUser?) {
    if (user == null) render401("login required")
}

Java 中实现 Render

SmartWeb 用 Kotlin 编译时没有开启接口默认方法,Java 看到的 Render 有 invoke 和 render 两个抽象方法,不能写成 lambda。Java 项目需要像上例那样写匿名类,render() 中抛出 ActionResult(rain.controller.special.ActionResult)。可以在项目里封装一个抽象基类,避免重复。

内置的 render302(location)、render401(body)、render403(body) 会设置状态码并立即结束流程。它们是 smartweb.controller.render 包中的顶层函数,Java 通过 RenderKt 调用。

统一错误响应 ​

公共 API 建议约定一个错误结构,再用 Render 输出:

kotlin
data class ApiError(val code: String, val message: String?)

fun apiError(status: Int, error: ApiError) = Render { context, _ ->
    context.resp.status = status
    error
}

在 Catch 中调用 apiError(...).render(),就能把领域异常转换为带状态码的 JSON 错误,见 Catch。这样 Action 不必直接操作 Response,也绕开了 String 的类型猜测。

500 错误 ​

没有被 Catch 处理的异常会变成 500,堆栈会打印到标准错误输出。

  • 开发模式(rain.runMode=dev):响应体是转换成 HTML 换行的堆栈文本
  • 其他模式:响应体是 JSON 文本 null

不要依赖默认的 500 响应对外报错,领域异常应通过 Catch 和统一 Render 转换。

与 Spring MVC 的差异 ​

Spring MVC 用 HandlerMethodReturnValueHandler、HttpMessageConverter、ViewResolver 和内容协商处理返回值。SmartWeb 只有一段按类型分派的逻辑,加上 Render 一个扩展出口。代码好读,但没有 Accept 内容协商、编码器注册、Range、ETag 等能力,公共 API 应在项目层封装统一的 Render。

基于 Apache License 2.0 发布