springboot 路由 json
阿新 • • 發佈:2020-07-22
一、前提條件
1、開啟熱載入
2、配置mybatis-plus 見 mybatis的部落格
二、路由
1、導包
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.60</version> </dependency>
2、controller 類中新增 註解
知識點
@Controller // 用於重定向和返回html @RestController //用於返回字串 @RequestMapping("/test") // 通用路由 @GetMapping("/json") // get請求的路由 @RequestParam // 請求引數 ? @PathVariable("name") // restful 風格的請求引數 引數 在url中
案例
a、注入
@Autowired // 注入 private UserMapper userMapper;
b、查詢
/* 1. restful風格的get請求 2. 請求url http://localhost:8083/test/json/wt 3. 用到知識點: @RequestMapper 用於做二級路由(Django的叫法) @GetMapper get請求的專屬路由 @PathVariable restful 風格傳遞引數*/ @GetMapping("/json/{name}") public String selectByName(@PathVariable("name") String name){ QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.eq("name", name); List<User> user = userMapper.selectList(wrapper); System.out.println(user);return JSON.toJSONString(user); } /* 根據 id 查詢 使用者資訊 * 1. 非restful 風格 的請求 * 2. 訪問路徑 http://localhost:8083/test/json?userId=5 * 3. @RequestParam 請求引數 ? * */ @GetMapping("/json") public String selectById(@RequestParam("userId") int id){ QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.eq("id", id); User user = userMapper.selectOne(wrapper); return JSON.toJSONString(user); }
c、增加
/* 普通 post 資料 1. @PostMapping post請求專用路由 2. @RequestParam 請求引數 ? */ @PostMapping("/post") public String insertUser( @RequestParam("username") String name, @RequestParam("age") int age, @RequestParam("email") String email ) { User user = new User(); user.setName(name); user.setAge(age); user.setEmail(email); userMapper.insert(user); List<User> userList = userMapper.selectList(null); return JSON.toJSONString(userList); } /* restful 風格的 post @PostMapping post 路由 @RequestBody 請求體, 預設為 json格式 工具 postman { "name": "erty123", "age": 45, "email": "[email protected]" } */ @PostMapping("/insert") public String insertUser2(@RequestBody User user){ userMapper.insert(user); return JSON.toJSONString(user); }
d、修改