Monday, July 5, 2010

Spring 3: RESTful Web service Support Part-2


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.

01package javaitzen.spring.rest.controller;
02
03import java.util.Map;
04import java.util.TreeMap;
05
06import javaitzen.spring.rest.User;
07
08import org.springframework.stereotype.Controller;
09import org.springframework.web.bind.annotation.PathVariable;
10import org.springframework.web.bind.annotation.RequestBody;
11import org.springframework.web.bind.annotation.RequestMapping;
12import org.springframework.web.bind.annotation.RequestMethod;
13import org.springframework.web.bind.annotation.ResponseBody;
14
15@Controller
16public 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}
You can view the results in your browser by simply going to the url. I am using weblogic, so mine looks like "http://localhost:7001/Spring3RESTFul-1/app/users/Mary" but depending on your deployment it could differ as long as you add "/app/users/Mary" to your context root you should get the following displayed. (if you are using firefox)

No comments:

Post a Comment