|
| 1 | +package org.baeldung.web.controller; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +import org.baeldung.model.Employee; |
| 7 | +import org.springframework.stereotype.Controller; |
| 8 | +import org.springframework.ui.ModelMap; |
| 9 | +import org.springframework.validation.BindingResult; |
| 10 | +import org.springframework.web.bind.annotation.ModelAttribute; |
| 11 | +import org.springframework.web.bind.annotation.PathVariable; |
| 12 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 13 | +import org.springframework.web.bind.annotation.RequestMethod; |
| 14 | +import org.springframework.web.bind.annotation.ResponseBody; |
| 15 | +import org.springframework.web.servlet.ModelAndView; |
| 16 | + |
| 17 | +@Controller |
| 18 | +public class EmployeeController { |
| 19 | + |
| 20 | + Map<Long, Employee> employeeMap = new HashMap<>(); |
| 21 | + |
| 22 | + @RequestMapping(value = "/employee", method = RequestMethod.GET) |
| 23 | + public ModelAndView showForm() { |
| 24 | + return new ModelAndView("employeeHome", "employee", new Employee()); |
| 25 | + } |
| 26 | + |
| 27 | + @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) |
| 28 | + public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { |
| 29 | + return employeeMap.get(Id); |
| 30 | + } |
| 31 | + |
| 32 | + @RequestMapping(value = "/employee/{Id}", method = RequestMethod.GET) |
| 33 | + public String getEmployeeByIdHtmlView(@PathVariable final long Id, final ModelMap model) { |
| 34 | + model.addAttribute("name", employeeMap.get(Id).getName()); |
| 35 | + model.addAttribute("contactNumber", employeeMap.get(Id).getContactNumber()); |
| 36 | + model.addAttribute("id", employeeMap.get(Id).getId()); |
| 37 | + |
| 38 | + return "employeeView"; |
| 39 | + } |
| 40 | + |
| 41 | + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) |
| 42 | + public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { |
| 43 | + if (result.hasErrors()) { |
| 44 | + return "error"; |
| 45 | + } |
| 46 | + model.addAttribute("name", employee.getName()); |
| 47 | + model.addAttribute("contactNumber", employee.getContactNumber()); |
| 48 | + model.addAttribute("id", employee.getId()); |
| 49 | + |
| 50 | + employeeMap.put(employee.getId(), employee); |
| 51 | + |
| 52 | + return "employeeView"; |
| 53 | + } |
| 54 | + |
| 55 | +} |
0 commit comments