Controller 开发实践
This content is not available in your language yet.
本指南介绍如何使用 Feat Cloud 的 Controller 注解来处理 HTTP 请求,包括路由映射、参数绑定、拦截器等常用功能。
核心注解概览
Section titled “核心注解概览”| 注解 | 作用 |
|---|---|
@Controller | 标记类为控制器 |
@RequestMapping | 定义请求路由 |
@Param | 绑定查询参数 |
@PathParam | 绑定路径参数 |
@InterceptorMapping | 配置拦截器 |
@PostConstruct / @PreDestroy | 生命周期管理 |
使用 @Controller 注解标记类为控制器:
// 基础用法@Controllerpublic class UserController { }
// 指定基础路径@Controller("/api")public class ApiController { }
// 启用 gzip 压缩(响应大于 512 字节时压缩)@Controller(value = "/api", gzip = true, gzipThreshold = 512)public class CompressedController { }参数说明:
value: Controller 基础路径gzip: 是否启用 gzip 压缩,默认falsegzipThreshold: 压缩阈值(字节),默认 256
使用 @RequestMapping 注解将方法映射到 HTTP 请求路径:
@Controller("/api")public class ApiController {
// 处理所有 HTTP 方法 @RequestMapping("/users") public String getAllUsers() { return "所有用户列表"; }
// 只处理 POST 请求 @RequestMapping(value = "/users", method = RequestMethod.POST) public String createUser() { return "创建用户"; }
// 处理多种 HTTP 方法 @RequestMapping(value = "/users/{id}", method = {RequestMethod.GET, RequestMethod.PUT}) public String getOrUpdateUser(@PathParam("id") String id) { return "操作用户: " + id; }}支持的 HTTP 方法: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
绑定查询参数
Section titled “绑定查询参数”使用 @Param 注解绑定 URL 查询参数:
@Controller("/api")public class ApiController {
// 单个参数 @RequestMapping("/search") public String search(@Param("keyword") String keyword) { return "搜索: " + keyword; }
// 多个参数 @RequestMapping("/filter") public String filter(@Param("category") String category, @Param("price") int price) { return "分类: " + category + ", 价格: " + price; }}对象参数自动绑定(无需 @Param):
@RequestMapping("/user")public String createUser(User user) { return "创建用户: " + user.getName() + ", 年龄: " + user.getAge();}绑定路径参数
Section titled “绑定路径参数”使用 @PathParam 注解绑定 URL 路径参数:
@Controller("/api")public class ApiController {
// 单个路径参数 @RequestMapping("/users/{id}") public String getUserById(@PathParam("id") String userId) { return "获取用户ID: " + userId; }
// 多个路径参数 @RequestMapping("/users/{userId}/orders/{orderId}") public String getOrder(@PathParam("userId") String userId, @PathParam("orderId") String orderId) { return "用户 " + userId + " 的订单 " + orderId; }}使用 @InterceptorMapping 注解为特定路径添加拦截器:
@Controller("/api")public class ApiController {
@RequestMapping("/users") public String getUsers() { return "用户列表"; }
@InterceptorMapping({"/api/users/*", "/api/admin/*"}) public Interceptor authInterceptor() { return (context, completableFuture, chain) -> { // 前置处理:权限验证 String token = context.Request.getHeader("Authorization"); if (token == null || !isValidToken(token)) { context.Response.setStatus(401); context.Response.write("Unauthorized".getBytes()); completableFuture.complete(null); return; }
// 继续执行请求链 chain.proceed(context, completableFuture);
// 后置处理:记录访问日志 System.out.println("API 访问完成: " + context.Request.getRequestURI()); }; }}注意事项:
- 路径匹配支持通配符(如
/path/*) - 多个拦截器按定义顺序执行
- 正确处理
CompletableFuture以支持异步请求
生命周期管理
Section titled “生命周期管理”使用 @PostConstruct 和 @PreDestroy 管理控制器生命周期:
@Controllerclass DemoController {
@PostConstruct public void init() { System.out.println("Controller 初始化完成"); // 执行初始化操作:加载配置、建立连接等 }
@RequestMapping("/test") public String test() { return "hello"; }
@PreDestroy public void destroy() { System.out.println("Controller 正在销毁"); // 执行清理操作:关闭连接、释放资源等 }}RESTful API 示例
Section titled “RESTful API 示例”@Controller("/api/users")public class UserController {
// GET /api/users - 获取所有用户 @RequestMapping(method = RequestMethod.GET) public List<User> getAllUsers() { return userService.getAllUsers(); }
// POST /api/users - 创建用户 @RequestMapping(method = RequestMethod.POST) public User createUser(User user) { return userService.createUser(user); }
// GET /api/users/{id} - 获取特定用户 @RequestMapping(value = "/{id}", method = RequestMethod.GET) public User getUser(@PathParam("id") String id) { return userService.getUserById(id); }
// PUT /api/users/{id} - 更新用户 @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public User updateUser(@PathParam("id") String id, User user) { return userService.updateUser(id, user); }
// DELETE /api/users/{id} - 删除用户 @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public void deleteUser(@PathParam("id") String id) { userService.deleteUser(id); }}统一返回格式示例
Section titled “统一返回格式示例”@Controller("/api")public class ApiController {
@RequestMapping("/users") public RestResult<List<User>> getUsers() { try { List<User> users = userService.getAllUsers(); return RestResult.ok(users); } catch (Exception e) { return RestResult.error(e.getMessage()); } }}如何处理跨域请求?
Section titled “如何处理跨域请求?”Fe at Cloud 暂不支持注解级别的跨域配置,可通过拦截器实现:
@InterceptorMapping("/*")public Interceptor corsInterceptor() { return (context, completableFuture, chain) -> { context.Response.setHeader("Access-Control-Allow-Origin", "*"); context.Response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); chain.proceed(context, completableFuture); };}如何获取请求头和请求体?
Section titled “如何获取请求头和请求体?”@RequestMapping("/api/data")public String processRequest(HttpRequest request) { // 获取请求头 String contentType = request.getHeader("Content-Type");
// 获取请求体 byte[] body = request.getBody();
return "处理完成";}有关完整示例,请参见 Controller 测试代码