Created
January 31, 2016 01:52
-
-
Save vy-nguyen/9ab3797f891e6c50d401 to your computer and use it in GitHub Desktop.
Form handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// list page | |
@RequestMapping(value = "/users", method = RequestMethod.GET) | |
public String showAllUsers(Model model) { | |
logger.debug("showAllUsers()"); | |
model.addAttribute("users", userService.findAll()); | |
return "users/list"; | |
} | |
// save or update user | |
// 1. @ModelAttribute bind form value | |
// 2. @Validated form validator | |
// 3. RedirectAttributes for flash value | |
@RequestMapping(value = "/users", method = RequestMethod.POST) | |
public String saveOrUpdateUser(@ModelAttribute("userForm") @Validated User user, | |
BindingResult result, Model model, | |
final RedirectAttributes redirectAttributes) { | |
logger.debug("saveOrUpdateUser() : {}", user); | |
if (result.hasErrors()) { | |
populateDefaultModel(model); | |
return "users/userform"; | |
} else { | |
// Add message to flash scope | |
redirectAttributes.addFlashAttribute("css", "success"); | |
if(user.isNew()){ | |
redirectAttributes.addFlashAttribute("msg", "User added successfully!"); | |
}else{ | |
redirectAttributes.addFlashAttribute("msg", "User updated successfully!"); | |
} | |
userService.saveOrUpdate(user); | |
// POST/REDIRECT/GET | |
return "redirect:/users/" + user.getId(); | |
// POST/FORWARD/GET | |
// return "user/list"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment