标记该 class为处理http请求的对象
@RestController Spring4后加入的注解,原来@Controller中返回 json需要返回@ResponseBody。使用@RestController不需要配置,自动默认返回 json。
RESTful api设计:
请求类型 | URL | 功能说明 |
---|---|---|
GET | /users | 查询用户列表 |
POST | /users | 创建一个用户 |
GET | /users/id | 根据 id查询用户 |
PUT | /users/id | 根据 id更新用户 |
DELETE | /users/id | 根据 id删除用户 |
@RestController@RequestMapping("/users")public class UserController { //创建线程安全的 map static Mapusers = Collections.synchronizedMap(new HashMap ()); @RequestMapping(value = "/", method = RequestMethod.GET) public List getUserList() { ArrayList users = new ArrayList (UserController.users.values()); return users; } @RequestMapping(value = "/", method = RequestMethod.POST) public String postUser(@ModelAttribute User user) { users.put(user.getId(), user); return "success"; } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public User getUser(@PathVariable Long id) { return users.get(id); } @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public String putUser(@PathVariable Long id, @ModelAttribute User user) { User u = users.get(id); u.setName(user.getName()); u.setAge(user.getAge()); users.put(id, u); return "success"; } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public String deleteUser(@PathVariable Long id) { users.remove(id); return "success"; }}