@RequestMapping(value = "/users/{id}", method = RequestMethod.POST) public String updateUser( @ModelAttribute("user") User user, BindingResult result, Model model, RedirectAttributes redirectAttributes) { if (result.hasErrors()) { return viewPrefix + "edit_user"; } User persistedUser = securityService.updateUser(user); logger.debug( "Updated user with id : {} and name : {}", persistedUser.getId(), persistedUser.getName()); redirectAttributes.addFlashAttribute("info", "User updates successfully"); return "redirect:/users"; }
@RequestMapping(value = "/users", method = RequestMethod.POST) public String createUser( @Valid @ModelAttribute("user") User user, BindingResult result, Model model, RedirectAttributes redirectAttributes) { userValidator.validate(user, result); if (result.hasErrors()) { return viewPrefix + "create_user"; } String password = user.getPassword(); String encodedPwd = passwordEncoder.encode(password); user.setPassword(encodedPwd); User persistedUser = securityService.createUser(user); logger.debug( "Created new User with id : {} and name : {}", persistedUser.getId(), persistedUser.getName()); redirectAttributes.addFlashAttribute("info", "User created successfully"); return "redirect:/users"; }
@RequestMapping(value = "/users/{id}", method = RequestMethod.GET) public String editUserForm(@PathVariable Integer id, Model model) { User user = securityService.getUserById(id); Map<Integer, Role> assignedRoleMap = new HashMap<>(); List<Role> roles = user.getRoles(); for (Role role : roles) { assignedRoleMap.put(role.getId(), role); } List<Role> userRoles = new ArrayList<>(); List<Role> allRoles = securityService.getAllRoles(); for (Role role : allRoles) { if (assignedRoleMap.containsKey(role.getId())) { userRoles.add(role); } else { userRoles.add(null); } } user.setRoles(userRoles); model.addAttribute("user", user); // model.addAttribute("rolesList",allRoles); return viewPrefix + "edit_user"; }