|
| 1 | +package com.xncoding.pos.controller; |
| 2 | + |
| 3 | +import com.xncoding.pos.model.BaseResponse; |
| 4 | +import com.xncoding.pos.model.User; |
| 5 | +import org.slf4j.Logger; |
| 6 | +import org.slf4j.LoggerFactory; |
| 7 | +import org.springframework.web.bind.annotation.*; |
| 8 | + |
| 9 | +import java.util.*; |
| 10 | + |
| 11 | +/** |
| 12 | + * 接口类 |
| 13 | + */ |
| 14 | +@RestController |
| 15 | +@RequestMapping(value = "/users") |
| 16 | +public class UserController { |
| 17 | + |
| 18 | + private static final Logger _logger = LoggerFactory.getLogger(UserController.class); |
| 19 | + |
| 20 | + // 创建线程安全的Map |
| 21 | + private static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>()); |
| 22 | + |
| 23 | + @RequestMapping(value = "/", method = RequestMethod.GET) |
| 24 | + public BaseResponse<List<User>> getUserList() { |
| 25 | + // 处理"/users/"的GET请求,用来获取用户列表 |
| 26 | + // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递 |
| 27 | + List<User> r = new ArrayList<>(users.values()); |
| 28 | + return new BaseResponse<>(true, "查询列表成功", r); |
| 29 | + } |
| 30 | + |
| 31 | + @RequestMapping(value = "/", method = RequestMethod.POST) |
| 32 | + public BaseResponse<String> postUser(@ModelAttribute User user) { |
| 33 | + // 处理"/users/"的POST请求,用来创建User |
| 34 | + // 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数 |
| 35 | + users.put(user.getId(), user); |
| 36 | + return new BaseResponse<>(true, "新增成功", ""); |
| 37 | + } |
| 38 | + |
| 39 | + @RequestMapping(value = "/{id}", method = RequestMethod.GET) |
| 40 | + public BaseResponse<User> getUser(@PathVariable Long id) { |
| 41 | + // 处理"/users/{id}"的GET请求,用来获取url中id值的User信息 |
| 42 | + // url中的id可通过@PathVariable绑定到函数的参数中 |
| 43 | + return new BaseResponse<>(true, "查询成功", users.get(id)); |
| 44 | + } |
| 45 | + |
| 46 | + @RequestMapping(value = "/{id}", method = RequestMethod.PUT) |
| 47 | + public BaseResponse<String> putUser(@PathVariable Long id, @ModelAttribute User user) { |
| 48 | + // 处理"/users/{id}"的PUT请求,用来更新User信息 |
| 49 | + User u = users.get(id); |
| 50 | + u.setName(user.getName()); |
| 51 | + u.setAge(user.getAge()); |
| 52 | + users.put(id, u); |
| 53 | + return new BaseResponse<>(true, "更新成功", ""); |
| 54 | + } |
| 55 | + |
| 56 | + @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) |
| 57 | + public BaseResponse<String> deleteUser(@PathVariable Long id) { |
| 58 | + // 处理"/users/{id}"的DELETE请求,用来删除User |
| 59 | + users.remove(id); |
| 60 | + return new BaseResponse<>(true, "删除成功", ""); |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments