controller_adjust
Change-Id: Ie136f68887cd547576239ad0ce0c2eaccde730b3
diff --git a/src/main/java/com/example/g8backend/controller/AuthController.java b/src/main/java/com/example/g8backend/controller/AuthController.java
index 5561dcd..538d433 100644
--- a/src/main/java/com/example/g8backend/controller/AuthController.java
+++ b/src/main/java/com/example/g8backend/controller/AuthController.java
@@ -1,5 +1,6 @@
package com.example.g8backend.controller;
+import com.example.g8backend.dto.ApiResponse;
import com.example.g8backend.dto.UserRegisterDTO;
import com.example.g8backend.entity.User;
import com.example.g8backend.entity.UserStats;
@@ -9,7 +10,6 @@
import com.example.g8backend.util.mailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
@@ -23,80 +23,88 @@
@Autowired
private IUserService userService;
+
@Autowired
private IUserStatsService userStatsService;
+
@Autowired
private mailUtil mailUtil;
+
@Autowired
private PasswordEncoder passwordEncoder;
+
@Autowired
private JwtUtil jwtUtil;
+
@Autowired
- RedisTemplate<String, Object> redisTemplate;
+ private RedisTemplate<String, Object> redisTemplate;
// 发送验证码
@PostMapping("/send_verification_code")
- public ResponseEntity<?> sendVerificationCode(@RequestBody UserRegisterDTO registerDTO) {
+ public ApiResponse<String> sendVerificationCode(@RequestBody UserRegisterDTO registerDTO) {
if (userService.getUserByEmail(registerDTO.getEmail()) != null) {
- return ResponseEntity.badRequest().body("邮箱已存在");
+ return ApiResponse.error(400, "邮箱已存在");
}
String verificationCode = UUID.randomUUID().toString().substring(0, 6);
mailUtil.sendMail(registerDTO.getEmail(), "PT平台注册验证码", "您的验证码为:" + verificationCode + ",验证码十分钟内有效,请勿泄露。");
redisTemplate.opsForValue().set(registerDTO.getEmail(), verificationCode, 10 * 60, java.util.concurrent.TimeUnit.SECONDS);
- return ResponseEntity.ok("验证码发送成功");
+ return ApiResponse.success("验证码发送成功");
}
// 用户注册
@PostMapping("/register")
- public ResponseEntity<?> register(@RequestBody UserRegisterDTO registerDTO) {
+ public ApiResponse<String> register(@RequestBody UserRegisterDTO registerDTO) {
if (userService.getUserByName(registerDTO.getUserName()) != null) {
- return ResponseEntity.badRequest().body("用户名已存在");
+ return ApiResponse.error(400, "用户名已存在");
}
if (!redisTemplate.hasKey(registerDTO.getInvitationCode())) {
- return ResponseEntity.badRequest().body("邀请码错误");
+ return ApiResponse.error(400, "邀请码错误");
}
- if (!registerDTO.getVerificationCode().equals(redisTemplate.opsForValue().get(registerDTO.getEmail()))) {
- return ResponseEntity.badRequest().body("验证码错误");
+
+ Object cachedCode = redisTemplate.opsForValue().get(registerDTO.getEmail());
+ if (!registerDTO.getVerificationCode().equals(cachedCode)) {
+ return ApiResponse.error(400, "验证码错误");
}
+
redisTemplate.delete(registerDTO.getEmail());
User user = new User();
user.setUserName(registerDTO.getUserName());
user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
user.setEmail(registerDTO.getEmail());
-
- // passkey 用于在客户端发送announce请求时获取用户信息
user.setPasskey(UUID.randomUUID().toString().replace("-", ""));
userService.save(user);
- // 保存用户统计用户的上传量与下载量
UserStats userStats = new UserStats();
userStats.setUserId(user.getUserId());
userStats.setPasskey(user.getPasskey());
userStatsService.save(userStats);
- return ResponseEntity.ok("注册成功");
+ return ApiResponse.message("注册成功");
}
// 用户登录
@PostMapping("/login")
- public ResponseEntity<?> login(@RequestBody User user) {
+ public ApiResponse<Map<String, String>> login(@RequestBody User user) {
User existingUser = userService.getUserByEmail(user.getEmail());
if (existingUser == null || !passwordEncoder.matches(user.getPassword(), existingUser.getPassword())) {
- return ResponseEntity.badRequest().body("用户名或密码错误");
+ return ApiResponse.error(400, "用户名或密码错误");
}
+
String token = jwtUtil.generateToken(existingUser.getUserId());
Map<String, String> response = new HashMap<>();
response.put("token", token);
- return ResponseEntity.ok(response);
+
+ return ApiResponse.success(response);
}
+ // 测试 Redis
@GetMapping("/test_redis")
- public ResponseEntity<?> testRedis() {
- redisTemplate.opsForValue().get("test");
- return ResponseEntity.ok("test redis ok");
+ public ApiResponse<String> testRedis() {
+ Object value = redisTemplate.opsForValue().get("test");
+ return ApiResponse.success("test redis ok");
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/com/example/g8backend/controller/ForgotPasswordController.java b/src/main/java/com/example/g8backend/controller/ForgotPasswordController.java
index 1d4cf58..5ca8a8e 100644
--- a/src/main/java/com/example/g8backend/controller/ForgotPasswordController.java
+++ b/src/main/java/com/example/g8backend/controller/ForgotPasswordController.java
@@ -1,27 +1,28 @@
package com.example.g8backend.controller;
+import com.example.g8backend.dto.ApiResponse;
import com.example.g8backend.dto.ForgotPasswordDTO;
import com.example.g8backend.dto.ResetPasswordDTO;
import com.example.g8backend.service.IForgotPasswordService;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/forgot-password")
public class ForgotPasswordController {
+
@Autowired
private IForgotPasswordService forgotPasswordService;
@PostMapping("/send-code")
- public ResponseEntity<?> sendCode(@RequestBody ForgotPasswordDTO dto) {
+ public ApiResponse<String> sendCode(@RequestBody ForgotPasswordDTO dto) {
forgotPasswordService.sendCodeToEmail(dto.getUsername());
- return ResponseEntity.ok("验证码已发送到注册邮箱");
+ return ApiResponse.success("验证码已发送到注册邮箱");
}
@PostMapping("/reset")
- public ResponseEntity<?> resetPassword(@RequestBody ResetPasswordDTO dto) {
+ public ApiResponse<String> resetPassword(@RequestBody ResetPasswordDTO dto) {
forgotPasswordService.resetPassword(dto.getUsername(), dto.getCode(), dto.getNewPassword());
- return ResponseEntity.ok("密码重置成功");
+ return ApiResponse.success("密码重置成功");
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/com/example/g8backend/controller/PostController.java b/src/main/java/com/example/g8backend/controller/PostController.java
index 68e0f95..9ac733f 100644
--- a/src/main/java/com/example/g8backend/controller/PostController.java
+++ b/src/main/java/com/example/g8backend/controller/PostController.java
@@ -1,151 +1,152 @@
package com.example.g8backend.controller;
+
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.example.g8backend.dto.ApiResponse;
import com.example.g8backend.dto.PostCreateDTO;
import com.example.g8backend.dto.PostHistoryDTO;
+import com.example.g8backend.entity.Post;
import com.example.g8backend.entity.PostView;
import com.example.g8backend.mapper.PostViewMapper;
+import com.example.g8backend.service.IPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
-import com.example.g8backend.entity.Post;
-import com.example.g8backend.service.IPostService;
+
import java.util.List;
+
@RestController
@RequestMapping("/post")
public class PostController {
+
@Autowired
private IPostService postService;
- @Autowired // ✅ 新增注入
+
+ @Autowired
private PostViewMapper postViewMapper;
+
@PostMapping("")
- public ResponseEntity<?> createPost(@RequestBody PostCreateDTO postCreateDTO) {
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- long userId = (long) authentication.getPrincipal();
+ public ResponseEntity<ApiResponse<Void>> createPost(@RequestBody PostCreateDTO postCreateDTO) {
+ long userId = (long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Post post = postCreateDTO.getPost();
Long[] tagIds = postCreateDTO.getTagIds();
post.setUserId(userId);
- if (tagIds.length > 0){
+ if (tagIds.length > 0) {
postService.createPost(post, tagIds);
} else {
postService.createPost(post);
}
- return ResponseEntity.ok().build();
+ return ResponseEntity.ok(ApiResponse.message("Post created successfully."));
}
+
@GetMapping("/{postId}")
- public Post getPost(@PathVariable Long postId) {
- // 获取当前用户ID
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- long userId = (long) authentication.getPrincipal();
- // 记录浏览行为
+ public ResponseEntity<ApiResponse<Post>> getPost(@PathVariable Long postId) {
+ long userId = (long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
postService.recordViewHistory(userId, postId);
- // 返回帖子详情
- return postService.getById(postId);
+ Post post = postService.getById(postId);
+ return ResponseEntity.ok(ApiResponse.success(post));
}
+
@DeleteMapping("/{postId}")
- public ResponseEntity<?> deletePost(@PathVariable("postId") Long postId) {
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- long userId = (long) authentication.getPrincipal();
+ public ResponseEntity<ApiResponse<String>> deletePost(@PathVariable Long postId) {
+ long userId = (long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Post post = postService.getById(postId);
if (post == null) {
- return ResponseEntity.status(500).body("Post not found.");
+ return ResponseEntity.status(404).body(ApiResponse.error(404, "Post not found."));
}
- if (post.getUserId()!= userId) {
- return ResponseEntity.status(403).body("You are not authorized to delete this post.");
+ if (post.getUserId() != userId) {
+ return ResponseEntity.status(403).body(ApiResponse.error(403, "You are not authorized to delete this post."));
}
postService.removeById(postId);
- return ResponseEntity.ok().body("Post deleted successfully.");
+ return ResponseEntity.ok(ApiResponse.message("Post deleted successfully."));
}
- @GetMapping("/getAll")
- public List<Post> getAllPosts() {
- return postService.list();
- }
- @GetMapping("/getByUserId/{userId}")
- public List<Post> getPostsByUserId(@PathVariable("userId") Long userId) {
- return postService.getPostsByUserId(userId);
- }
- @PutMapping("/{postId}")
- public ResponseEntity<?> updatePost(@PathVariable("postId") Long postId, @RequestBody Post post) {
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- long userId = (long) authentication.getPrincipal();
- Post existingPost = postService.getById(postId);
+ @GetMapping("/getAll")
+ public ResponseEntity<ApiResponse<List<Post>>> getAllPosts() {
+ return ResponseEntity.ok(ApiResponse.success(postService.list()));
+ }
+
+ @GetMapping("/getByUserId/{userId}")
+ public ResponseEntity<ApiResponse<List<Post>>> getPostsByUserId(@PathVariable Long userId) {
+ return ResponseEntity.ok(ApiResponse.success(postService.getPostsByUserId(userId)));
+ }
+
+ @PutMapping("/{postId}")
+ public ResponseEntity<ApiResponse<String>> updatePost(@PathVariable Long postId, @RequestBody Post post) {
+ long userId = (long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
+ Post existingPost = postService.getById(postId);
if (existingPost == null) {
- return ResponseEntity.status(500).body("Post not found.");
+ return ResponseEntity.status(404).body(ApiResponse.error(404, "Post not found."));
}
if (existingPost.getUserId() != userId) {
- return ResponseEntity.status(403).body("You are not authorized to update this post.");
+ return ResponseEntity.status(403).body(ApiResponse.error(403, "You are not authorized to update this post."));
}
post.setPostId(postId);
post.setUserId(userId);
postService.updateById(post);
- return ResponseEntity.ok().body("Post updated successfully.");
+ return ResponseEntity.ok(ApiResponse.message("Post updated successfully."));
}
+
@GetMapping("/type/{postType}")
- public ResponseEntity<?> getPostsByType(@PathVariable String postType) {
+ public ResponseEntity<ApiResponse<List<Post>>> getPostsByType(@PathVariable String postType) {
List<Post> posts = postService.getPostsByType(postType);
- return ResponseEntity.ok().body(posts);
+ return ResponseEntity.ok(ApiResponse.success(posts));
}
+
@PostMapping("/{postId}/like")
- public ResponseEntity<?> likePost(@PathVariable Long postId) {
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- long userId = (long) authentication.getPrincipal();
+ public ResponseEntity<ApiResponse<String>> likePost(@PathVariable Long postId) {
+ long userId = (long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
postService.likePost(userId, postId);
- return ResponseEntity.ok().body("Post liked successfully.");
+ return ResponseEntity.ok(ApiResponse.message("Post liked successfully."));
}
+
@DeleteMapping("/{postId}/like")
- public ResponseEntity<?> unlikePost(@PathVariable Long postId) {
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- long userId = (long) authentication.getPrincipal();
+ public ResponseEntity<ApiResponse<String>> unlikePost(@PathVariable Long postId) {
+ long userId = (long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
postService.unlikePost(userId, postId);
- return ResponseEntity.ok().body("Post unliked successfully.");
+ return ResponseEntity.ok(ApiResponse.message("Post unliked successfully."));
}
+
@GetMapping("/{postId}/likes")
- public ResponseEntity<?> getPostLikeCount(@PathVariable Long postId) {
+ public ResponseEntity<ApiResponse<Long>> getPostLikeCount(@PathVariable Long postId) {
Long likeCount = postService.getPostLikeCount(postId);
- return ResponseEntity.ok().body(likeCount);
+ return ResponseEntity.ok(ApiResponse.success(likeCount));
}
- // 搜索帖子
+
@GetMapping("/search")
- public List<Post> searchPosts(
+ public ResponseEntity<ApiResponse<List<Post>>> searchPosts(
@RequestParam(required = false) String keyword,
- @RequestParam(required = false) List<Long> tags, // 修改为接收多个标签
+ @RequestParam(required = false) List<Long> tags,
@RequestParam(required = false) String author) {
- return postService.searchPosts(keyword, tags, author);
+ List<Post> result = postService.searchPosts(keyword, tags, author);
+ return ResponseEntity.ok(ApiResponse.success(result));
}
@GetMapping("/history")
- public ResponseEntity<List<PostHistoryDTO>> getViewHistory() {
- // 获取当前用户ID
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- long userId = (long) authentication.getPrincipal();
-
- // 调用Service层
+ public ResponseEntity<ApiResponse<List<PostHistoryDTO>>> getViewHistory() {
+ long userId = (long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
List<PostHistoryDTO> history = postService.getViewHistoryWithTitles(userId);
- return ResponseEntity.ok(history);
+ return ResponseEntity.ok(ApiResponse.success(history));
}
+
@GetMapping("/recommended")
- public ResponseEntity<Page<Post>> getRecommendedPosts(
+ public ResponseEntity<ApiResponse<Page<Post>>> getRecommendedPosts(
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int size) {
- // 获取当前用户ID
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- long userId = (long) authentication.getPrincipal();
- // 调用 Service 层方法
+ long userId = (long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Page<Post> pageResult = postService.getRecommendedPosts(page, size, userId);
- return ResponseEntity.ok(pageResult);
+ return ResponseEntity.ok(ApiResponse.success(pageResult));
}
+
@GetMapping("/recommended-by-tags")
- public ResponseEntity<Page<Post>> getRecommendedByTags(
+ public ResponseEntity<ApiResponse<Page<Post>>> getRecommendedByTags(
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int size) {
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- long userId = (long) authentication.getPrincipal();
- // 调用标签推荐方法
+ long userId = (long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Page<Post> result = postService.getRecommendedByTags(page, size, userId);
- return ResponseEntity.ok(result);
+ return ResponseEntity.ok(ApiResponse.success(result));
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/com/example/g8backend/controller/TorrentController.java b/src/main/java/com/example/g8backend/controller/TorrentController.java
index 7640e42..ea7fdf2 100644
--- a/src/main/java/com/example/g8backend/controller/TorrentController.java
+++ b/src/main/java/com/example/g8backend/controller/TorrentController.java
@@ -1,15 +1,15 @@
package com.example.g8backend.controller;
+import com.example.g8backend.dto.ApiResponse;
import com.example.g8backend.entity.User;
import com.example.g8backend.entity.Torrent;
import com.example.g8backend.service.IUserService;
+import com.example.g8backend.service.ITorrentService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
-import com.example.g8backend.service.ITorrentService;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
@@ -20,14 +20,16 @@
@RestController
@RequestMapping("/torrent")
public class TorrentController {
+
@Autowired
private ITorrentService torrentService;
@Autowired
private IUserService userService;
- @RequestMapping("/upload")
- public ResponseEntity<?> handleTorrentUpload(@RequestParam("file") MultipartFile multipartFile) throws IOException {
+ // 处理种子文件上传
+ @PostMapping("/upload")
+ public ApiResponse<String> handleTorrentUpload(@RequestParam("file") MultipartFile multipartFile) throws IOException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
long userId = (long) authentication.getPrincipal();
@@ -39,11 +41,11 @@
try {
assert fileName != null;
} catch (AssertionError e) {
- return ResponseEntity.badRequest().body("文件名不能为空");
+ return ApiResponse.error(400, "文件名不能为空");
}
if (!fileName.endsWith(".torrent")) {
- return ResponseEntity.badRequest().body("文件格式不正确,请上传.torrent格式的文件");
+ return ApiResponse.error(400, "文件格式不正确,请上传.torrent格式的文件");
}
File tempFile = File.createTempFile("upload-", ".torrent");
@@ -52,16 +54,17 @@
try {
torrentService.handleTorrentUpload(tempFile, fileName, userId, passkey);
} catch (IllegalArgumentException e) {
- return ResponseEntity.badRequest().body(e.getMessage());
+ return ApiResponse.error(400, e.getMessage());
}
// 删除临时文件
- if(!tempFile.delete()){
+ if (!tempFile.delete()) {
throw new IOException("Failed to delete temporary file: " + tempFile.getAbsolutePath());
}
- return ResponseEntity.ok("种子上传成功");
+ return ApiResponse.success("种子上传成功");
}
+ // 下载种子文件
@GetMapping("/download/{torrentId}")
public void downloadTorrent(@PathVariable String torrentId, HttpServletResponse response) throws IOException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
diff --git a/src/main/java/com/example/g8backend/controller/UserController.java b/src/main/java/com/example/g8backend/controller/UserController.java
index 0473025..121bc1a 100644
--- a/src/main/java/com/example/g8backend/controller/UserController.java
+++ b/src/main/java/com/example/g8backend/controller/UserController.java
@@ -1,10 +1,10 @@
package com.example.g8backend.controller;
+import com.example.g8backend.dto.ApiResponse;
import com.example.g8backend.entity.Message;
import com.example.g8backend.entity.User;
import com.example.g8backend.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
@@ -21,65 +21,68 @@
// 获取已登录的用户信息
@GetMapping
- public ResponseEntity<?> getUserInfo(){
+ public ApiResponse<User> getUserInfo(){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
long userId = (long) authentication.getPrincipal();
User user = userService.getById(userId);
- user.setPassword(null);
- return ResponseEntity.ok(user);
+ user.setPassword(null); // 不返回密码
+ return ApiResponse.success(user);
}
+
// ==================== 关注功能 ====================
+
@PostMapping("/follow/{userId}")
- public ResponseEntity<?> followUser(@PathVariable Long userId) {
+ public ApiResponse<Map<String, Boolean>> followUser(@PathVariable Long userId) {
Long currentUserId = getCurrentUserId();
boolean success = userService.followUser(currentUserId, userId);
- return ResponseEntity.ok(Map.of("success", success));
+ return ApiResponse.success(Map.of("success", success));
}
@DeleteMapping("/follow/{userId}")
- public ResponseEntity<?> unfollowUser(@PathVariable Long userId) {
+ public ApiResponse<Map<String, Boolean>> unfollowUser(@PathVariable Long userId) {
Long currentUserId = getCurrentUserId();
boolean success = userService.unfollowUser(currentUserId, userId);
- return ResponseEntity.ok(Map.of("success", success));
+ return ApiResponse.success(Map.of("success", success));
}
@GetMapping("/followings")
- public ResponseEntity<?> getFollowings() {
+ public ApiResponse<List<User>> getFollowings() {
Long currentUserId = getCurrentUserId();
List<User> followings = userService.getFollowings(currentUserId);
- return ResponseEntity.ok(followings);
+ return ApiResponse.success(followings);
}
@GetMapping("/followers")
- public ResponseEntity<?> getFollowers() {
+ public ApiResponse<List<User>> getFollowers() {
Long currentUserId = getCurrentUserId();
List<User> followers = userService.getFollowers(currentUserId);
- return ResponseEntity.ok(followers);
+ return ApiResponse.success(followers);
}
// ==================== 私信功能 ====================
+
@PostMapping("/message/{receiverId}")
- public ResponseEntity<?> sendMessage(
+ public ApiResponse<Map<String, Long>> sendMessage(
@PathVariable Long receiverId,
@RequestBody String content
) {
Long senderId = getCurrentUserId();
Long messageId = userService.sendMessage(senderId, receiverId, content);
- return ResponseEntity.ok(Map.of("messageId", messageId));
+ return ApiResponse.success(Map.of("messageId", messageId));
}
@GetMapping("/messages/{otherUserId}")
- public ResponseEntity<?> getMessages(@PathVariable Long otherUserId) {
+ public ApiResponse<List<Message>> getMessages(@PathVariable Long otherUserId) {
Long currentUserId = getCurrentUserId();
List<Message> messages = userService.getMessages(currentUserId, otherUserId);
- return ResponseEntity.ok(messages);
+ return ApiResponse.success(messages);
}
@GetMapping("/messages/history")
- public ResponseEntity<?> getMessageHistory() {
+ public ApiResponse<List<Message>> getMessageHistory() {
Long currentUserId = getCurrentUserId();
List<Message> messages = userService.getMessageHistory(currentUserId);
- return ResponseEntity.ok(messages);
+ return ApiResponse.success(messages);
}
// ==================== 工具方法 ====================
diff --git a/src/main/java/com/example/g8backend/controller/UserSecurityController.java b/src/main/java/com/example/g8backend/controller/UserSecurityController.java
index 34bbb96..0f41549 100644
--- a/src/main/java/com/example/g8backend/controller/UserSecurityController.java
+++ b/src/main/java/com/example/g8backend/controller/UserSecurityController.java
@@ -1,9 +1,9 @@
package com.example.g8backend.controller;
import com.example.g8backend.dto.PasswordChangeDTO;
+import com.example.g8backend.dto.ApiResponse;
import com.example.g8backend.service.IUserSecurityService;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
@@ -11,14 +11,19 @@
@RestController
@RequestMapping("/user/security")
public class UserSecurityController {
+
@Autowired
private IUserSecurityService userSecurityService;
@PutMapping("/change-password")
- public ResponseEntity<?> changePassword(@RequestBody PasswordChangeDTO dto) {
+ public ApiResponse<String> changePassword(@RequestBody PasswordChangeDTO dto) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Long userId = (Long) authentication.getPrincipal();
+
+ // 调用服务层进行密码修改
userSecurityService.changePassword(userId, dto.getOldPassword(), dto.getNewPassword());
- return ResponseEntity.ok("密码修改成功");
+
+ // 返回统一的成功响应
+ return ApiResponse.success("密码修改成功");
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/com/example/g8backend/dto/ApiResponse.java b/src/main/java/com/example/g8backend/dto/ApiResponse.java
new file mode 100644
index 0000000..fb6ed0e
--- /dev/null
+++ b/src/main/java/com/example/g8backend/dto/ApiResponse.java
@@ -0,0 +1,33 @@
+package com.example.g8backend.dto;
+
+public class ApiResponse<T> {
+ private int code;
+ private String message;
+ private T data;
+
+ public ApiResponse() {}
+
+ public ApiResponse(int code, String message, T data) {
+ this.code = code;
+ this.message = message;
+ this.data = data;
+ }
+
+ public static <T> ApiResponse<T> success(T data) {
+ return new ApiResponse<>(200, "Success", data);
+ }
+
+ public static <T> ApiResponse<T> success(String message, T data) {
+ return new ApiResponse<>(200, message, data);
+ }
+
+ public static <T> ApiResponse<T> message(String message) {
+ return new ApiResponse<>(200, message, null);
+ }
+
+ public static <T> ApiResponse<T> error(int code, String message) {
+ return new ApiResponse<>(code, message, null);
+ }
+
+ // Getters and Setters 略,也可使用 Lombok 注解
+}
\ No newline at end of file