UserController:
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
//获取所有用户的列表
@GetMapping
public ModelAndView list(@RequestParam(value = "async", required = false) boolean async,
@RequestParam(value = "pageIndex", required = false, defaultValue = "0") int pageIndex,
@RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize,
@RequestParam(value = "name", required = false, defaultValue = "") String name,
Model model
){
Pageable pageable = new PageRequest(pageIndex, pageSize);
Page<User> page = userService.listUserByNameLike(name, pageable);
List<User> list = page.getContent();
model.addAttribute("page", page);
model.addAttribute("userList", list);
return new ModelAndView(async==true?"users/list :: #mainContainerRepleace":"users/list", "userModel", model);
}
//获取创建表单页面
@GetMapping("/add")
public ModelAndView createForm(Model model){
model.addAttribute("user", new User(null, null, null, null));
return new ModelAndView("users/add","userModel",model);
}
//保存或修改用户
@PostMapping
public ResponseEntity<Response> saveOrUpdate(User user){
try {
userService.saveOrUpdate(user);
}catch (ConstraintViolationException e){
return ResponseEntity.ok().body(new Response(false, ConstraintViolationExceptionHandler.getMessage(e)));
}
return ResponseEntity.ok().body(new Response(true, "处理成功", user));
}
//删除用户
@DeleteMapping(value = "/{id}")
public ResponseEntity<Response> delete(@PathVariable("id") Long id, Model model){
try {
userService.removeUser(id);
}catch (Exception e){
return ResponseEntity.ok().body(new Response(false, e.getMessage()));
}
return ResponseEntity.ok().body(new Response(true, "处理成功"));
}
//获取修改用户的页面
@GetMapping("/edit/{id}")
public ModelAndView modifyForm(@PathVariable("id") Long id, Model model){
User user = userService.getUserById(id);
model.addAttribute("user", user);
return new ModelAndView("users/edit", "userModel", model);
}
}
AdminController:
@Controller
@RequestMapping("/admins")
public class AdminController {
@GetMapping
public ModelAndView listUsers(Model model){
List<Menu> list = new ArrayList<Menu>();
list.add(new Menu("用户管理","/users"));
model.addAttribute("list", list);
return new ModelAndView("/admins/index", "model", model);
}
}