| 1 | package info.ahlberg.spring.controller; |
| 2 | |
| 3 | import java.util.List; |
| 4 | |
| 5 | import info.ahlberg.spring.domain.Contact; |
| 6 | import info.ahlberg.spring.service.ContactService; |
| 7 | |
| 8 | import org.springframework.beans.factory.annotation.Autowired; |
| 9 | import org.springframework.stereotype.Controller; |
| 10 | import org.springframework.ui.Model; |
| 11 | import org.springframework.web.bind.annotation.RequestMapping; |
| 12 | import org.springframework.web.bind.annotation.RequestParam; |
| 13 | import org.springframework.web.bind.annotation.ResponseBody; |
| 14 | |
| 15 | @Controller |
| 16 | @RequestMapping("/") |
| 17 | public class ContactController { |
| 18 | @Autowired |
| 19 | private ContactService contactService; |
| 20 | |
| 21 | @RequestMapping("/") |
| 22 | String index(Model model) { |
| 23 | model.addAttribute("msg", "A nice message"); |
| 24 | |
| 25 | model.addAttribute("contacts", contactService.findAll()); |
| 26 | |
| 27 | return "index"; |
| 28 | } |
| 29 | |
| 30 | @RequestMapping("/contacts") |
| 31 | @ResponseBody List<Contact> contacts(Model model) { |
| 32 | return contactService.findAll(); |
| 33 | } |
| 34 | |
| 35 | @RequestMapping("/add") |
| 36 | String add(@RequestParam String name, Model model) { |
| 37 | model.addAttribute("msg", "A nice message"); |
| 38 | |
| 39 | Contact contact = new Contact(); |
| 40 | contact.setName(name); |
| 41 | contactService.save(contact); |
| 42 | |
| 43 | model.addAttribute("contacts", contactService.findAll()); |
| 44 | |
| 45 | return "index"; |
| 46 | } |
| 47 | } |
| 48 | |