|
| 1 | +package com.baeldung.springmvcforms.controller; |
| 2 | + |
| 3 | +import javax.validation.Valid; |
| 4 | + |
| 5 | +import org.springframework.beans.factory.annotation.Autowired; |
| 6 | +import org.springframework.stereotype.Controller; |
| 7 | +import org.springframework.ui.ModelMap; |
| 8 | +import org.springframework.validation.BindingResult; |
| 9 | +import org.springframework.web.bind.annotation.ModelAttribute; |
| 10 | +import org.springframework.web.bind.annotation.PostMapping; |
| 11 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 12 | +import org.springframework.web.bind.annotation.RequestMethod; |
| 13 | +import org.springframework.web.servlet.ModelAndView; |
| 14 | + |
| 15 | +import com.baeldung.springmvcforms.domain.Customer; |
| 16 | +import com.baeldung.springmvcforms.validator.CustomerValidator; |
| 17 | + |
| 18 | +@Controller |
| 19 | +public class CustomerController { |
| 20 | + |
| 21 | + @Autowired |
| 22 | + CustomerValidator validator; |
| 23 | + |
| 24 | + @RequestMapping(value = "/customer", method = RequestMethod.GET) |
| 25 | + public ModelAndView showForm() { |
| 26 | + return new ModelAndView("customerHome", "customer", new Customer()); |
| 27 | + } |
| 28 | + |
| 29 | + @PostMapping("/addCustomer") |
| 30 | + public String submit(@Valid @ModelAttribute("customer") final Customer customer, final BindingResult result, final ModelMap model) { |
| 31 | + validator.validate(customer, result); |
| 32 | + if (result.hasErrors()) { |
| 33 | + return "customerHome"; |
| 34 | + } |
| 35 | + model.addAttribute("customerId", customer.getCustomerId()); |
| 36 | + model.addAttribute("customerName", customer.getCustomerName()); |
| 37 | + model.addAttribute("customerContact", customer.getCustomerContact()); |
| 38 | + model.addAttribute("customerEmail", customer.getCustomerEmail()); |
| 39 | + return "customerView"; |
| 40 | + } |
| 41 | + |
| 42 | +} |
0 commit comments