发表于: 2025-05-03 20:06:39
0 80
今天完成的事情:(一定要写非常细致的内容,比如说学会了盒子模型,了解了Margin)
写出spring-mvc.xml
package org.example.controller;
import org.example.model.ApiResponse;
import org.example.model.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
// 查询用户
@GetMapping("/{id}")
public ApiResponse<User> getUser(@PathVariable Integer id) {
User user = userService.getUserById(id);
if (user != null) {
return ApiResponse.success(user);
} else {
return ApiResponse.error(404, "用户不存在");
}
}
// 创建用户
@PostMapping("/")
public ApiResponse<Map<String, Object>> createUser(@RequestBody User user) {
try {
int result = userService.addUser(user);
if (result > 0) {
// 获取新建的完整用户数据(这里我们只需要ID)
Integer id = user.getId(); // 假设user对象在添加后已经包含了数据库生成的ID
// 构造包含 id 的响应
Map<String, Object> response = new HashMap<>();
response.put("id", id);
return ApiResponse.success(response);
} else {
return ApiResponse.error(500, "创建失败");
}
} catch (Exception e) {
return ApiResponse.error(400, "参数错误: " + e.getMessage());
}
}
// 更新用户
@PutMapping("/{id}")
public ApiResponse<Map<String, Object>> updateUser(@PathVariable Integer id, @RequestBody User user) {
try {
// 设置 ID,确保更新的是正确的记录
user.setId(id);
// 执行更新操作
int result = userService.updateUser(user);
if (result > 0) {
// 直接返回ID,不再查询完整用户数据
Map<String, Object> response = new HashMap<>();
response.put("id", id);
return ApiResponse.success(response);
} else {
return ApiResponse.error(500, "更新失败,请检查ID是否存在或字段是否有改动");
}
} catch (Exception e) {
// 打印异常堆栈信息以便定位问题
e.printStackTrace();
return ApiResponse.error(400, "更新失败: " + e.getMessage());
}
}
// 删除用户
@DeleteMapping("/{id}")
public ApiResponse<Void> deleteUser(@PathVariable Integer id) {
int result = userService.deleteUser(id);
if (result > 0) {
return ApiResponse.success();
} else {
return ApiResponse.error(500, "删除失败");
}
}
}
明天计划的事情:(一定要写非常细致的内容)
跑通任务
遇到的问题:(遇到什么困难,怎么解决的)
收获:(通过今天的学习,学到了什么知识)
完成了spring-mvc.xml
评论