发表于: 2025-04-27 20:53:13
0 95
今天完成的事情:(一定要写非常细致的内容,比如说学会了盒子模型,了解了Margin)
根据接口文档,使用Spring Rest 编写对应的Controller,日志记录接收参数后,暂时不用写业务逻辑,直接返回JSP,直接用Json Tag-lib 生成假数据
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.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public ModelAndView getUser(@PathVariable Integer id) {
User user = userService.getUserById(id);
if (user != null) {
return buildResponse("user/detail", ApiResponse.success(user));
}
return buildResponse("user/error", ApiResponse.error(404, "用户不存在"));
}
@PostMapping
public ModelAndView createUser(@RequestBody User user) {
try {
int result = userService.addUser(user);
if (result > 0) {
return buildResponse("user/result",
ApiResponse.success(new UserCreateResult(user.getId())));
}
return buildResponse("user/error", ApiResponse.error(500, "创建用户失败"));
} catch (Exception e) {
return buildResponse("user/error",
ApiResponse.error(400, "参数错误: " + e.getMessage()));
}
}
@PutMapping("/{id}")
public ModelAndView updateUser(@PathVariable Integer id, @RequestBody User user) {
try {
user.setId(id);
int result = userService.updateUser(user);
if (result > 0) {
return buildResponse("user/result",
ApiResponse.success(userService.getUserById(id)));
}
return buildResponse("user/error", ApiResponse.error(404, "用户不存在"));
} catch (Exception e) {
return buildResponse("user/error",
ApiResponse.error(400, "更新失败: " + e.getMessage()));
}
}
@DeleteMapping("/{id}")
public ModelAndView deleteUser(@PathVariable Integer id) {
int result = userService.deleteUser(id);
if (result > 0) {
return buildResponse("user/result", ApiResponse.success(null));
}
return buildResponse("user/error", ApiResponse.error(404, "用户不存在"));
}
// 辅助方法
private ModelAndView buildResponse(String viewName, ApiResponse response) {
ModelAndView mav = new ModelAndView(viewName);
mav.addObject("jsonData", response);
return mav;
}
// 内部类用于创建响应
private static class UserCreateResult {
private final Integer id;
public UserCreateResult(Integer id) {
this.id = id;
}
// getter
public Integer getId() {
return id;
}
}
}
明天计划的事情:(一定要写非常细致的内容)
遇到的问题:(遇到什么困难,怎么解决的)
Javac识别不出来
收获:(通过今天的学习,学到了什么知识)
评论