HTTP 接口与响应
Feat Cloud 的 HTTP 开发可以从一个简单的约定开始:用 @Controller 声明控制器,用 @RequestMapping 声明接口。请求进入方法后,参数由框架绑定;方法返回后,结果再被写入 HTTP 响应。
这一章把请求的入口和出口放在一起讲。因为对业务开发者来说,它们本来就是同一条链路:客户端发来什么,业务方法如何接收,方法返回什么,客户端最终得到什么。
从一个接口开始
Section titled “从一个接口开始”下面是一个最小控制器。访问 /users/hello 时,Feat Cloud 会调用 hello() 并返回文本。
package com.example.controller;
import tech.smartboot.feat.cloud.annotation.Controller;import tech.smartboot.feat.cloud.annotation.RequestMapping;import tech.smartboot.feat.cloud.annotation.RequestMethod;
@Controller("users")public class UserController {
@RequestMapping(value = "/hello", method = RequestMethod.GET) public String hello() { return "hello controller"; }}启动应用后,可以在控制台看到路由注册信息:
Feat Router: |-> /users/hello ==> UserController@hello验证接口:
curl -i http://localhost:8080/users/hello@Controller 的 value 是控制器下所有接口的路径前缀。比如控制器路径为 api/v1、方法路径为 /users,最终路径就是 /api/v1/users。控制器路径为空时,方法路径就是完整路径。
一个业务接口通常需要处理三类输入:查询参数、路径参数和请求体。
查询参数与表单参数
Section titled “查询参数与表单参数”使用 @Param 从请求参数中取值:
@RequestMapping(value = "/search", method = RequestMethod.GET)public String search(@Param("keyword") String keyword, @Param("page") Integer page) { int currentPage = page == null ? 1 : page; return "搜索: " + keyword + ", 页码: " + currentPage;}请求:
curl "http://localhost:8080/users/search?keyword=feat&page=1"当请求的 Content-Type 不是 JSON 时,@Param 从 URL 查询参数或表单参数中取值;当请求使用 application/json 时,它从 JSON 对象中读取对应字段。因此,同一个注解也可以用于表单和 JSON 请求体。
可能缺失的参数建议使用 Integer、Long、Boolean 等包装类型。若使用 int 这类基本类型,缺失参数返回的 null 在拆箱时可能触发 NullPointerException。
路径中的动态部分使用 @PathParam 接收:
@RequestMapping(value = "/:userId", method = RequestMethod.GET)public String getUser(@PathParam("userId") String userId) { return "用户ID: " + userId;}Feat Cloud 支持冒号和花括号两种路径写法:
/:userId/{userId}
两种形式等价。路径参数目前支持 String、int / Integer 和 long / Long;数值转换失败时使用 0 作为默认值,其他类型暂不支持。
JSON 请求体
Section titled “JSON 请求体”创建或更新资源时,通常把数据放在 JSON 请求体中。Controller 方法可以直接声明一个自定义 POJO 参数,不需要额外注解:
public class User { private String username; private String role;
public String getUsername() { return username; } public void setUsername(String username) { this.username = username; }
public String getRole() { return role; } public void setRole(String role) { this.role = role; }}@RequestMapping(value = "/", method = RequestMethod.POST)public String create(User user) { return "created user: " + user.getUsername();}调用时需要带上 Content-Type: application/json:
curl -X POST http://localhost:8080/users/ \ -H 'Content-Type: application/json' \ -d '{"username":"Bob","role":"admin"}'HTTP 方法
Section titled “HTTP 方法”RequestMethod 支持 GET、HEAD、POST、PUT、PATCH、DELETE、OPTIONS 和 TRACE。
@RequestMapping.method 默认为空数组。不指定 method 时,路由不限制 HTTP 方法。 如果接口只应该响应某一种或几种请求方法,请显式声明:
@RequestMapping(value = "/", method = RequestMethod.GET)public String list() { return "list users";}
@RequestMapping(value = "/", method = RequestMethod.POST)public String create(User user) { return "created user: " + user.getUsername();}
@RequestMapping(value = "/:id", method = RequestMethod.DELETE)public String delete(@PathParam("id") String id) { return "deleted user: " + id;}请求参数解决的是输入问题。接下来要看 Controller 返回值如何变成 HTTP 响应。
文本、对象与集合
Section titled “文本、对象与集合”最简单的接口可以直接返回 String:
@RequestMapping(value = "/ping", method = RequestMethod.GET)public String ping() { return "pong";}返回自定义对象、集合或 Map 时,Feat Cloud 会将其序列化为 JSON:
@RequestMapping(value = "/info", method = RequestMethod.GET)public Map<String, Object> info() { Map<String, Object> data = new HashMap<>(); data.put("framework", "Feat Cloud"); data.put("type", "aot-web"); return data;}统一业务响应
Section titled “统一业务响应”如果接口会被前端、移动端或其他服务长期依赖,建议使用稳定的响应结构。Feat Cloud 提供 RestResult<T>,包含四个字段:
| 字段 | 含义 |
|---|---|
success | 业务是否成功 |
code | 业务响应码 |
message | 失败说明 |
data | 成功时返回的数据 |
import tech.smartboot.feat.cloud.RestResult;
@RequestMapping("/{username}")public RestResult<User> getUser(@PathParam("username") String username) { User user = findUser(username); if (user == null) { return RestResult.fail("User not found"); } return RestResult.ok(user);}成功响应示例:
{ "success": true, "code": 200, "message": null, "data": { "username": "feat", "role": "admin" }}失败响应示例:
{ "success": false, "code": 500, "message": "User not found", "data": null}RestResult.fail(...) 表达的是业务失败,不等同于 HTTP 传输失败。客户端仍然会收到结构稳定的 JSON,可以根据 success 和 code 处理业务结果。
不是所有接口都必须使用 RestResult。健康检查、纯文本响应和简单调试接口可以直接返回文本;文件下载、图片和静态资源则应使用相应的底层响应能力。关键是让调用方能够稳定理解接口契约。
编译期生成与序列化
Section titled “编译期生成与序列化”Feat Cloud 不会在每次请求到来时重新扫描 Controller 注解。编译阶段,注解处理器会解析 Controller、请求映射和方法签名,生成 CloudService 实现类;应用启动时再加载生成结果并注册路由。
返回值的处理也遵循相同思路。对于结构明确的类型,编译期可以生成字段访问和写出代码。可以把它理解为:你编写业务返回值,框架提前替你生成“如何把它写入响应流”的样板代码。
常见类型的处理方式如下:
| 返回类型 / 字段类型 | 处理方式 |
|---|---|
Controller 返回 String、byte[] | 直接转换为字节并写入响应流 |
Controller 返回基本类型 int、boolean | 使用专门的直接写出逻辑 |
包装类型(如 Integer、Long)、Date / Timestamp | 回退到 FastJSON2;POJO 字段中的对应类型按专用生成逻辑处理 |
| 自定义 POJO | 根据 getter 生成字段访问与写出代码 |
| POJO 字段中的数值包装类型、布尔值 | 生成直接取值与写出代码 |
POJO 字段中的 Date、Timestamp | 默认写出毫秒时间戳;可用 @JSONField(format = "...") 指定格式 |
声明了泛型的 List<T> | 生成遍历代码,元素类型继续按对应规则处理 |
Map、数组、Object、未声明泛型的 List、嵌套过深对象 | 回退到 FastJSON2 |
例如,RestResult<List<Map<String, String>>> 中,RestResult 和声明了泛型的 List 可以走生成代码;其中每个 Map 则交给 FastJSON2 的 JSONObject 处理。
需要特别注意嵌套层数。当前实测的分界线是三层已展开的 DTO:
RestResult → LoginResponse → CurrentUserResponse → List<MenuItem>:列表元素回退到 FastJSON2;RestResult → CurrentUserResponse → List<MenuItem>:列表元素逐字段写出。
两种路径的字段集合可能不同:FastJSON2 默认省略值为 null 的字段,而生成代码会写出 "permission": null。因此,同一个 DTO 在不同接口上的 JSON 形状可能不一致。建议 DTO 嵌套不要超过两层;需要表达“没有值”时,优先考虑空串或空集合,并在接口契约中明确约定。
AsyncResponse 的完成结果发生在运行时,编译期无法提前知道具体对象结构,因此会走运行时 JSON 序列化。
按需使用运行时能力
Section titled “按需使用运行时能力”日常接口通常只需要请求绑定和返回值。当业务确实需要访问完整请求或控制响应行为时,再使用运行时能力。
访问 Context
Section titled “访问 Context”需要读取请求头、设置响应头或访问完整 URI 时,可以在 Controller 方法参数中声明 Context:
import tech.smartboot.feat.router.Context;
@RequestMapping(value = "/context", method = RequestMethod.GET)public String context(Context context) { String uri = context.Request.getRequestURI(); String method = context.Request.getMethod(); return "URI: " + uri + ", Method: " + method;}当方法需要调用远程服务或执行耗时操作时,可以返回 AsyncResponse,避免阻塞 Feat 的工作线程:
import tech.smartboot.feat.cloud.AsyncResponse;import tech.smartboot.feat.cloud.RestResult;import java.util.concurrent.CompletableFuture;
@RequestMapping(value = "/async", method = RequestMethod.GET)public AsyncResponse async() { AsyncResponse response = new AsyncResponse();
CompletableFuture.runAsync(() -> { try { Thread.sleep(1000); response.complete(RestResult.ok("异步响应完成")); } catch (InterruptedException e) { Thread.currentThread().interrupt(); response.complete(RestResult.fail("异步任务被中断")); } catch (Exception e) { response.complete(RestResult.fail("异步任务执行失败")); } });
return response;}生产环境应将 CompletableFuture.runAsync 替换为有容量和生命周期管理的自定义线程池,避免占满 common pool。
Gzip 压缩
Section titled “Gzip 压缩”可以在 @Controller 上开启 Gzip:
@Controller( value = "api", gzip = true, gzipThreshold = 256)public class ApiController { @RequestMapping(value = "/large", method = RequestMethod.GET) public String largeResponse() { return "这是一段较长的响应内容,用于演示 Gzip 压缩阈值和响应编码行为。"; }}也可以在 feat.yml 中全局配置:
server: gzip: true gzipThreshold: 1024默认阈值是 256 字节,低于阈值的响应不会压缩。全局开启后,server.gzipThreshold 会覆盖控制器注解上的阈值。可通过带有 Accept-Encoding: gzip 的请求验证:
curl -H "Accept-Encoding: gzip" http://localhost:8080/api/large --compressed到这里,请求从 HTTP 进入 Controller,再从方法返回值变成 HTTP 响应的基本过程就完整了。
- 需要组织业务对象和依赖关系,继续阅读Bean 与依赖注入。
- 需要把公共逻辑应用到多个方法,阅读方法拦截器。
- 需要理解生成类和应用启动过程,阅读编译期工作模型。
- 如果要直接控制底层 HTTP 请求处理,而不是使用 Controller 开发模型,请从 Feat Core 服务端开始。