1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
| package com.example.controller;
import com.example.common.ApiResponse; import com.example.entity.User; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameters; import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.ExampleObject; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.responses.ApiResponse as SwaggerApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotNull; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Optional;
@RestController @RequestMapping("/users") @Tag(name = "用户管理", description = "提供用户的增删改查功能,支持批量操作和高级查询 🎯") @Validated public class UserController { private final List<User> userDatabase = new ArrayList<>(); private Long idCounter = 1L; public UserController() { User user1 = new User("admin", "admin@example.com"); user1.setId(idCounter++); user1.setNickname("超级管理员"); user1.setAge(30); user1.setGender(User.Gender.MALE); user1.setPhone("13812345678"); User user2 = new User("alice", "alice@example.com"); user2.setId(idCounter++); user2.setNickname("小爱同学"); user2.setAge(25); user2.setGender(User.Gender.FEMALE); user2.setPhone("13987654321"); userDatabase.add(user1); userDatabase.add(user2); }
@GetMapping @Operation( summary = "获取用户列表", description = "支持分页查询和关键字搜索的用户列表接口。" + "\n\n**功能特点:**\n" + "- 🔍 支持用户名和昵称模糊搜索\n" + "- 📄 支持分页查询,避免数据量过大\n" + "- ⚡ 查询性能优化,响应速度快\n" + "- 📊 返回总数信息,方便前端分页处理", tags = {"用户查询"} ) @Parameters({ @Parameter( name = "page", description = "页码,从1开始", example = "1", in = ParameterIn.QUERY, schema = @Schema(type = "integer", minimum = "1", defaultValue = "1") ), @Parameter( name = "size", description = "每页大小,最大100", example = "10", in = ParameterIn.QUERY, schema = @Schema(type = "integer", minimum = "1", maximum = "100", defaultValue = "10") ), @Parameter( name = "keyword", description = "搜索关键字,支持用户名和昵称模糊搜索", example = "张三", in = ParameterIn.QUERY, schema = @Schema(type = "string") ) }) @ApiResponses({ @SwaggerApiResponse( responseCode = "200", description = "查询成功", content = @Content( mediaType = "application/json", schema = @Schema(implementation = ApiResponse.class), examples = @ExampleObject( name = "成功示例", summary = "查询成功的响应示例", value = """ { "code": 200, "message": "查询成功", "data": { "list": [ { "id": 1, "username": "admin", "nickname": "超级管理员", "email": "admin@example.com", "age": 30, "gender": "MALE", "status": "ACTIVE", "createTime": "2024-01-01 12:00:00" } ], "total": 1, "page": 1, "size": 10 }, "timestamp": "2024-01-01 12:00:00" } """ ) ) ), @SwaggerApiResponse( responseCode = "400", description = "参数错误", content = @Content( mediaType = "application/json", schema = @Schema(implementation = ApiResponse.class) ) ) }) public ResponseEntity<ApiResponse<PageResult<User>>> getUsers( @RequestParam(defaultValue = "1") @Min(value = 1, message = "页码必须大于0") Integer page, @RequestParam(defaultValue = "10") @Min(value = 1, message = "页大小必须大于0") Integer size, @RequestParam(required = false) String keyword) { List<User> filteredUsers = userDatabase; if (keyword != null && !keyword.trim().isEmpty()) { filteredUsers = userDatabase.stream() .filter(user -> user.getUsername().contains(keyword) || (user.getNickname() != null && user.getNickname().contains(keyword))) .toList(); } int start = (page - 1) * size; int end = Math.min(start + size, filteredUsers.size()); List<User> pagedUsers = filteredUsers.subList(start, end); PageResult<User> result = new PageResult<>(pagedUsers, (long) filteredUsers.size(), page, size); return ResponseEntity.ok(ApiResponse.success("查询成功", result)); }
@GetMapping("/{id}") @Operation( summary = "获取用户详情", description = "根据用户ID获取用户的详细信息。\n\n" + "**注意事项:**\n" + "- 用户ID必须是有效的正整数\n" + "- 如果用户不存在,会返回404错误\n" + "- 返回的数据包含用户的所有可见字段", tags = {"用户查询"} ) @Parameter( name = "id", description = "用户ID", example = "1", required = true, in = ParameterIn.PATH, schema = @Schema(type = "integer", format = "int64", minimum = "1") ) @ApiResponses({ @SwaggerApiResponse( responseCode = "200", description = "获取成功", content = @Content( mediaType = "application/json", schema = @Schema(implementation = ApiResponse.class), examples = @ExampleObject( name = "用户详情", value = """ { "code": 200, "message": "获取成功", "data": { "id": 1, "username": "admin", "nickname": "超级管理员", "email": "admin@example.com", "phone": "13812345678", "age": 30, "gender": "MALE", "status": "ACTIVE", "createTime": "2024-01-01 12:00:00", "updateTime": "2024-01-01 12:00:00" }, "timestamp": "2024-01-01 12:00:00" } """ ) ) ), @SwaggerApiResponse( responseCode = "404", description = "用户不存在", content = @Content( mediaType = "application/json", examples = @ExampleObject( value = """ { "code": 404, "message": "用户不存在", "data": null, "timestamp": "2024-01-01 12:00:00" } """ ) ) ) }) public ResponseEntity<ApiResponse<User>> getUserById( @PathVariable @NotNull(message = "用户ID不能为空") Long id) { Optional<User> userOpt = userDatabase.stream() .filter(user -> user.getId().equals(id)) .findFirst(); if (userOpt.isPresent()) { return ResponseEntity.ok(ApiResponse.success("获取成功", userOpt.get())); } else { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body(ApiResponse.notFound("用户不存在")); } }
@PostMapping @Operation( summary = "创建用户", description = "创建一个新的用户账户。\n\n" + "**验证规则:**\n" + "- 用户名:3-20字符,只能包含字母、数字和下划线\n" + "- 邮箱:必须是有效的邮箱格式\n" + "- 手机号:符合中国大陆手机号格式\n" + "- 年龄:1-150之间的整数\n\n" + "**注意:**\n" + "- 用户名和邮箱必须唯一\n" + "- 创建成功后会自动设置为ACTIVE状态\n" + "- 系统会自动设置创建时间和更新时间", tags = {"用户管理"} ) @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "用户信息", required = true, content = @Content( mediaType = "application/json", schema = @Schema(implementation = User.class), examples = { @ExampleObject( name = "基础用户", summary = "创建基础用户", value = """ { "username": "newuser", "nickname": "新用户", "email": "newuser@example.com", "phone": "13911112222", "age": 28, "gender": "FEMALE" } """ ), @ExampleObject( name = "完整用户", summary = "创建完整信息用户", value = """ { "username": "fulluser", "nickname": "完整用户", "email": "fulluser@example.com", "phone": "13800138000", "age": 35, "gender": "MALE" } """ ) } ) ) @ApiResponses({ @SwaggerApiResponse( responseCode = "201", description = "创建成功", content = @Content( mediaType = "application/json", schema = @Schema(implementation = ApiResponse.class) ) ), @SwaggerApiResponse( responseCode = "400", description = "参数验证失败", content = @Content( mediaType = "application/json", examples = @ExampleObject( value = """ { "code": 400, "message": "用户名已存在", "data": null, "timestamp": "2024-01-01 12:00:00" } """ ) ) ) }) public ResponseEntity<ApiResponse<User>> createUser(@Valid @RequestBody User user) { boolean usernameExists = userDatabase.stream() .anyMatch(u -> u.getUsername().equals(user.getUsername())); if (usernameExists) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(ApiResponse.badRequest("用户名已存在")); } boolean emailExists = userDatabase.stream() .anyMatch(u -> u.getEmail().equals(user.getEmail())); if (emailExists) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(ApiResponse.badRequest("邮箱已存在")); } user.setId(idCounter++); user.setStatus(User.UserStatus.ACTIVE); user.setCreateTime(LocalDateTime.now()); user.setUpdateTime(LocalDateTime.now()); userDatabase.add(user); return ResponseEntity.status(HttpStatus.CREATED) .body(ApiResponse.success("用户创建成功", user)); } @Schema(name = "PageResult", description = "分页查询结果") public static class PageResult<T> { @Schema(description = "数据列表") private List<T> list; @Schema(description = "总记录数", example = "100") private Long total; @Schema(description = "当前页码", example = "1") private Integer page; @Schema(description = "每页大小", example = "10") private Integer size; @Schema(description = "总页数", example = "10") private Integer totalPages; @Schema(description = "是否有下一页", example = "true") private Boolean hasNext; @Schema(description = "是否有上一页", example = "false") private Boolean hasPrev; public PageResult(List<T> list, Long total, Integer page, Integer size) { this.list = list; this.total = total; this.page = page; this.size = size; this.totalPages = (int) Math.ceil((double) total / size); this.hasNext = page < totalPages; this.hasPrev = page > 1; } public List<T> getList() { return list; } public Long getTotal() { return total; } public Integer getPage() { return page; } public Integer getSize() { return size; } public Integer getTotalPages() { return totalPages; } public Boolean getHasNext() { return hasNext; } public Boolean getHasPrev() { return hasPrev; } } }
|