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