| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- package com.malk.test;
- import com.malk.server.common.McR;
- import com.malk.test.dto.User;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.poi.ss.formula.functions.T;
- import org.springframework.context.annotation.Profile;
- import org.springframework.web.bind.annotation.*;
- import java.util.*;
- /**
- * RESTFul 风格 [取值详见CatchException]
- * -
- * 1. GET >>> /users >>> 查询用户列表
- * 2. POST >>> /users >>> 创建一个用户
- * 3. GET >>> /users/id 查询一个用户
- * 4. PUT/PATCH >>> /users/id 更新一个用户 [PUG全量更新, PATC增量更新]
- * 5. DELETE >>> /users/id 删除一个用户
- * -
- * 参数获取方式均相同, GET 没有 body, @PathVariable 获取 url 占位符, RequestParam 获取 url 参数, @RequestBody 获取 body 数据
- */
- @Slf4j
- @Profile({"dev", "test"})
- @RestController
- @RequestMapping("/test/users")
- public class RESTFulTestController {
- // 创建线程安全的Map
- static Map<Long, User> users = Collections.synchronizedMap(new HashMap<>());
- // 注解参考 MCTestController
- @ModelAttribute
- void userId(User user) {
- long id1 = (long) (Math.random() * 100);
- long id2 = new Random().nextInt(1000);
- log.info("Random, {}, {}", id1, id2);
- user.setId(id1 + id2);
- user.setName(String.valueOf(id2));
- user.setAge((int) id1);
- }
- public List<User> getUserList() {
- // 处理"/users/"的GET请求,用来获取用户列表
- // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递
- return new ArrayList<>(users.values());
- }
- @PostMapping
- public String postUser(@ModelAttribute User user) {
- // 处理"/users/"的POST请求,用来创建User
- // 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数
- users.put(user.getId(), user);
- return "success";
- }
- @GetMapping("{id}")
- public User getUser(@PathVariable Long id) {
- // 处理"/users/{id}"的GET请求,用来获取url中id值的User信息
- // url中的id可通过@PathVariable绑定到函数的参数中
- return users.get(id);
- }
- @RequestMapping(value = "{id}", method = {RequestMethod.PUT, RequestMethod.PATCH})
- public String putUser(@PathVariable Long id, @ModelAttribute User user, @RequestParam String param, @RequestBody Map<String, String> body) {
- log.info("PUT / PATCH, {}, {}, {}", id, param, body);
- // 处理"/users/{id}"的PUT请求,用来更新User信息
- User u = users.get(id);
- u.setName(user.getName());
- u.setAge(user.getAge());
- users.put(id, u);
- return "success";
- }
- @DeleteMapping("{id}")
- public String deleteUser(@PathVariable Long id, @RequestParam String param, @RequestBody Map<String, String> body) {
- log.info("delete, {}, {}, {}", id, param, body);
- // 处理"/users/{id}"的DELETE请求,用来删除User
- users.remove(id);
- return "success";
- }
- /**
- * test
- */
- @GetMapping("test")
- McR<T> test() {
- return McR.success();
- }
- }
|