Note: You really should not have a horrible static map containing state within a controller (like I do below), I am only doing it now because this is an example, and I want to keep it simple and not digress into a full blown application. If I have time over the next week or so, I'll remove that map of data and just create an embedded DB or something.
01 | package javaitzen.spring.rest.controller; |
02 |
03 | import java.util.Map; |
04 | import java.util.TreeMap; |
05 |
06 | import javaitzen.spring.rest.User; |
07 |
08 | import org.springframework.stereotype.Controller; |
09 | import org.springframework.web.bind.annotation.PathVariable; |
10 | import org.springframework.web.bind.annotation.RequestBody; |
11 | import org.springframework.web.bind.annotation.RequestMapping; |
12 | import org.springframework.web.bind.annotation.RequestMethod; |
13 | import org.springframework.web.bind.annotation.ResponseBody; |
14 |
15 | @Controller |
16 | public class UsersController { |
17 |
18 | private static Map<> users = new TreeMap<>(); |
19 | |
20 | @RequestMapping(value="/users/{firstName}",method=RequestMethod.GET) |
21 | @ResponseBody public User getUser(@PathVariable("firstName")String user) { |
22 | System.out.println("retrieve"); |
23 | User theUser = someExampleData().get(user); |
24 | return theUser; |
25 | |
26 | } |
27 | |
28 | @RequestMapping(value="/users/",method=RequestMethod.POST) |
29 | @ResponseBody public User createUser(@RequestBody User user) { |
30 | System.out.println("create"); |
31 | users.put(user.getFirstName(), user); |
32 | return user; |
33 | } |
34 | |
35 | @RequestMapping(value="/users/{firstName}",method=RequestMethod.PUT) |
36 | @ResponseBody public User updateUser(@PathVariable("firstName")String name, @RequestBody User user) { |
37 | System.out.println("update"); |
38 | users.put(user.getFirstName(), user); |
39 | return user; |
40 | } |
41 |
42 | @RequestMapping(value="/users/{firstName}",method=RequestMethod.DELETE) |
43 | @ResponseBody public voiddeleteUser(@PathVariable("firstName")String name) { |
44 | System.out.println("delete"); |
45 | users.remove(name); |
46 | |
47 | } |
48 | |
49 | /** |
50 | * Some example data. |
51 | * |
52 | * @return the map |
53 | */ |
54 | private Map<> someExampleData() { |
55 | users.put("Bob", new User("Bob", "Smith", "bobs", "clean","simple", "code")); |
56 | users.put("John", new User("John", "Doe", "johnd", "large","complicated", "code")); |
57 | users.put("Mary", new User("Mary", "Smith", "marys","nice", "pretty", "code")); |
58 | return users; |
59 | } |
60 | } |
No comments:
Post a Comment