WEB应用第九次作业

发布时间:2026/7/1 8:03:00

WEB应用第九次作业 采用restful风格完整自己项目的某个功能的增删改查的项目代码。一、改造核心规则新增统一全局返回体 ResultT抛弃各处手写 HashMap标准化 REST 返回URL 统一前缀/api资源用名词复数弃用/add /update /delete /listAll动词路径HTTP 方法严格语义GET查询单条 / 列表 / 登录信息POST新增、登录登录属于特殊创建会话保留 POSTPUT全量更新资源DELETE删除资源区分页面跳转接口与 API 接口原LoginController中toXXX页面跳转保留不归 REST API所有数据接口迁移至/api/user /api/admin提供 JSON废弃 Controller ResponseBody 组合API 统一使用RestController删除接口改用路径变量/api/user/{id} DELETE 请求不再 POST 传参底层 Dao、Service 逻辑完全不动仅修改 Controller 层前端同步修正请求 URL、请求 Method适配新 REST 接口二、新增通用返回类 Result.javapackage im.wust.common; public class ResultT { private Integer code; private String msg; private T data; // 无参构造 public Result() {} // Getter Setter public Integer getCode() { return code; } public void setCode(Integer code) { this.code code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg msg; } public T getData() { return data; } public void setData(T data) { this.data data; } // 成功返回带数据 public static T ResultT success(T data) { ResultT r new Result(); r.setCode(200); r.setMsg(操作成功); r.setData(data); return r; } // 成功无数据 public static T ResultT success() { return success(null); } // 失败返回默认500 public static T ResultT fail(String msg) { ResultT r new Result(); r.setCode(500); r.setMsg(msg); return r; } // 自定义状态码失败401未登录、400参数错误 public static T ResultT fail(Integer code, String msg) { ResultT r new Result(); r.setCode(code); r.setMsg(msg); return r; } }三、改造Controller1. ApiAdminController.java管理员 REST 接口package im.wust.controller; import im.wust.common.Result; import im.wust.pojo.Admin; import im.wust.service.AdminService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.sql.SQLException; RestController RequestMapping(/api/admin) public class ApiAdminController { Autowired private AdminService adminService; /** * POST 登录创建管理员会话符合REST特殊场景 * POST /api/admin/login */ PostMapping(/login) public ResultAdmin login(RequestParam String username, RequestParam String password) { try { Admin admin adminService.login(username, password); if (admin ! null) { return Result.success(admin); } else { return Result.fail(管理员账号或密码错误); } } catch (SQLException e) { e.printStackTrace(); return Result.fail(数据库访问异常); } } }2. ApiUserController.javapackage im.wust.controller; import im.wust.common.Result; import im.wust.pojo.User; import im.wust.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.sql.SQLException; import java.util.List; RestController RequestMapping(/api/users) CrossOrigin(origins *) public class ApiUserController { Autowired private UserService userService; /** * GET /api/users 查询全部用户 */ GetMapping public ResultListUser listAll() { try { ListUser userList userService.listAllUser(); return Result.success(userList); } catch (SQLException e) { e.printStackTrace(); return Result.fail(数据库查询异常); } } /** * POST /api/users 新增用户 */ PostMapping public ResultString add(RequestBody User user) { try { String res userService.addUser(user); if (success.equals(res)) { return Result.success(); } else { return Result.fail(res); } } catch (SQLException e) { e.printStackTrace(); return Result.fail(数据库新增异常); } } /** * PUT /api/users/{id} 全量更新用户 */ PutMapping(/{id}) public ResultString update(PathVariable Integer id, RequestBody User user) { try { user.setId(id); String res userService.updateUser(user); if (success.equals(res)) { return Result.success(); } else { return Result.fail(res); } } catch (SQLException e) { e.printStackTrace(); return Result.fail(数据库修改异常); } } /** * DELETE /api/users/{id} 删除用户 */ DeleteMapping(/{id}) public ResultString delete(PathVariable Integer id) { try { String res userService.deleteUser(id); if (success.equals(res)) { return Result.success(); } else { return Result.fail(res); } } catch (SQLException e) { e.printStackTrace(); return Result.fail(数据库删除异常); } } /** * POST /api/users/login 用户登录创建会话 */ PostMapping(/login) public ResultUser login(RequestParam String username, RequestParam String password) { try { User user userService.loginCheck(username, password); if (user ! null) { return Result.success(user); } else { return Result.fail(400, 账号或密码错误); } } catch (Exception e) { e.printStackTrace(); return Result.fail(数据库异常登录失败); } } /** * POST /api/users/register 用户注册新建用户资源 */ PostMapping(/register) public ResultString register(RequestBody User user) { try { String msg userService.register(user); if (success.equals(msg)) { return Result.success(); } else { return Result.fail(400, msg); } } catch (Exception e) { e.printStackTrace(); return Result.fail(数据库异常注册失败); } } /** * GET /api/users/current 获取当前登录用户信息 */ GetMapping(/current) public ResultUser getCurrentUser(jakarta.servlet.http.HttpSession session) { String loginName (String) session.getAttribute(loginUser); if (loginName null || loginName.isEmpty()) { return Result.fail(401, 未登录请先登录); } try { User user userService.getUserInfoByUsername(loginName); return Result.success(user); } catch (SQLException e) { e.printStackTrace(); return Result.fail(查询用户信息失败); } } }3. LoginController.java仅保留页面跳转移除数据接口package im.wust.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; Controller RequestMapping(/auth) public class LoginController { // 页面跳转接口不参与REST API GetMapping(/toRegister) public String toRegister() { return html/register; } GetMapping(/toLogin) public String toLoginPage() { return html/login(self); } GetMapping(/toShowInfo) public String toShowInfo() { return html/showinfo; } GetMapping(/toIndex) public String toIndexPage() { return html/index(self); } }四、Dao / Service / Pojo / DBUtil / 启动类 无需改动AdminDao、UserDao、Admin、User、AdminService、UserService、ServiceImpl、DBUtil、WebStart 业务逻辑完全不变不需要修改。五、前端 HTML 请求 URLMethod 同步修改1. login.html 用户登录原请求POST /user/login修改为axios({ method: post, url: /api/users/login, headers: { Content-Type: application/x-www-form-urlencoded }, data: new URLSearchParams({ username: trimName, password: password }) }).then(res { const data res.data if (data.code 200) { window.location.href index.html } else { showMsg(error, data.msg) } })2. register.html 用户注册原请求POST /user/register修改 url/api/users/registermethod 保持 POST 不变3. showinfo.html 获取当前用户原请求/user/getUserInfo修改 url/api/users/currentmethod 改为 GETfetch(/api/users/current) .then(res res.json()) .then(data { if (data.code 200) { userInfo.value data.data } else { showAlert(data.msg) window.location.href login.html } })4. managerlogin.html 管理员登录原请求/admin/login修改 url/api/admin/loginPOST 不变5. managerindex.html 后台用户管理查询全部用户 原fetch(/user/listAll)→GET /api/usersconst loadUserList () { fetch(/api/users) .then(res res.json()) .then(data { if(data.code 200) userTableData.value data.data else showTip(data.msg) }) }新增用户 原POST /user/add→POST /api/users修改用户 原POST /user/update→PUT /api/users/${editForm.value.id}fetch(/api/users/${editForm.value.id}, { method: PUT, headers: {Content-Type:application/json}, body: JSON.stringify(editForm.value) })删除用户 原POST /user/delete?idxx→DELETE /api/users/${delTargetId.value}fetch(/api/users/${delTargetId.value}, {method:DELETE})六、REST 改造对比总结旧接口新 REST 接口请求方式作用/admin/login/api/admin/loginPOST管理员登录/user/login/api/users/loginPOST用户登录/user/register/api/users/registerPOST用户注册/user/getUserInfo/api/users/currentGET获取登录用户/user/listAll/api/usersGET查询所有用户/user/add/api/usersPOST新增用户/user/update/api/users/{id}PUT修改用户/user/delete/api/users/{id}DELETE删除用户七、预览图

相关新闻