Skip to content

Instantly share code, notes, and snippets.

@vy-nguyen
Created January 30, 2016 20:44
Show Gist options
  • Save vy-nguyen/433e74fba2e3a4af1d72 to your computer and use it in GitHub Desktop.
Save vy-nguyen/433e74fba2e3a4af1d72 to your computer and use it in GitHub Desktop.
/**
* Form post handler
*/
@RequestMapping(value = "/", method = RequestMethod.POST)
public String send(
@Valid @ModelAttribute("messageForm") MessageForm messageForm,
BindingResult binding,
RedirectAttributes redirectAttributes) {
// Redirect back into form page if errors detected
if (binding.hasErrors()) {
redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.messageForm", binding);
redirectAttributes.addFlashAttribute("messageForm", messageForm);
return "redirect:/";
}
return "redirect:/result";
}
...
git clone https://gerrytan@bitbucket.org/gerrytan/formvalidation1.git
@Controller
public class GuestbookController {
/**
* Serve guestbook form.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model model) {
if(!model.containsAttribute("messageForm")) model.addAttribute("messageForm", new MessageForm());
return "guestbook";
}
// more code ..
}
public class MessageForm {
@NotBlank(message = "Please provide your name")
private String name;
@NotBlank(message = "Please provide your email")
@Email(message = "Invalid email address")
private String email;
@Size(min = 10, message = "Please enter at least 10 characters")
private String message;
// getters & setters..
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment