管理使用者前後端

佬zz發表於2024-07-23

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>User Management</title>
</head>
<body>
<h2>User Management</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Username</th>
<th>Name</th>
<th>Role</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.username}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.role}"></td>
<td>
<!-- Update Form -->
<form th:action="@{/admin/users/update}" method="post" th:object="${user}">
<input type="hidden" th:field="*{id}">
<select th:field="*{role}">
<option th:value="'ADMIN'" th:text="'Admin'" th:selected="${user.role == 'ADMIN'}"></option>
<option th:value="'USER'" th:text="'User'" th:selected="${user.role == 'USER'}"></option>
</select>
<button type="submit">Update</button>
</form>

<!-- Delete Form -->
<form th:action="@{/admin/users/delete}" method="post">
<input type="hidden" name="id" th:value="${user.id}">
<button type="submit">Delete</button>
</form>
</td>
</tr>
</tbody>
</table>
</body>
</html>

package com.example.meetingroombooking.controller;

import com.example.meetingroombooking.model.User;
import com.example.meetingroombooking.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/admin/users")
public class UserManagementController {

@Autowired
private UserService userService;

@GetMapping
public String listUsers(Model model) {
List<User> users = userService.getAllUsers();
model.addAttribute("users", users);
return "userManagement";
}

@PostMapping("/update")
public String updateUser(@ModelAttribute User user) {
userService.saveUser(user);
return "redirect:/admin/users";
}

@PostMapping("/delete")
public String deleteUser(@RequestParam Long id) {
userService.deleteUser(id);
return "redirect:/admin/users";
}
}

相關文章