概述

TestControler

在 Web 开发中,常用的类包括 HttpRequest, HttpResponse, Reps 等。以下是一个使用了 tio-boot controller 的 Java 控制器示例:

import com.litongjava.tio.http.server.annotation.RequestPath;
@AController
@RequestPath("/test")
public class TestController {

  @RequestPath
  public String index() {
    return "index";
  }
}

这段代码演示了一些重要的注解的用法:

  1. @AController: 这个注解标识一个类作为控制器(Controller)。如果一个类已经被 @RequestPath 注解标记,那么可以省略 @AController 注解。
  2. @RequestPath: 这个注解用于指明控制器的请求路径。在这个例子中,它将 TestController 类关联到了 /test 路径。此外,当一个控制器类的成员方法返回值不为 void 时,tio-boot 会自动将这些方法添加到请求路由中。方法名将作为子路径。你也可以通过在方法上使用 @RequestPath 来手动指定路由路径。

在 TIO HTTP Server 中,一个控制器(Controller)的方法(即 Action 方法)支持注入以下类型的参数:

  • ServerChannelContext
  • HttpConfig
  • HttpSession
  • HttpRequest

IndexController

import com.litongjava.tio.http.server.annotation.RequestPath;

@RequestPath("/")
public class IndexController {
  @RequestPath("")
  public String index() {
    return "uh-course";
  }
}

  1. 类声明和注解:

    • @RequestPath("/"): 这个注解将整个 IndexController 类映射到根路径 /。这意味着当请求的 URL 以 / 开头时,可能会由这个控制器处理。
  2. 方法声明和注解:

    • @RequestPath(""): 这个注解将 index 方法映射到相对路径为空的请求,即根路径 /。当请求 URL 是 / 时,这个方法会被调用。
    • public String index(): 这是一个公开的方法,它返回一个字符串 "uh-course"。这个字符串将作为 HTTP 响应的内容返回给客户端。

测试

>curl http://localhost/
uh-course
>curl http://localhost
uh-course