1:@GetMapping

处理get请求,传统的RequestMapping来编写应该是

@RequestMapping(value = "path" , method = RequestMethod.GET)

新方法可简写为:@GetMapping("path")

通常在查询数据时使用,例如:

/**
 * 根据ID查询
 * @param id
 * @return
 */
@GetMapping("/select/{id}")
MyStudent selectById(@PathVariable String id) {
    return myStudentMapper.selectByPrimaryKey(id);
}

2: @PostMapping

处理post请求,传统的RequestMapping来编写应该是

@RequestMapping(value = "path", method = RequestMethod.POST)

新方法可简写为:@PostMapping("path")

通常在新增数据时使用,例如:

/**
 * 插入数据
 * @param id
 * @param name
 * @param birth
 * @param sex
 * @return
 */
@PostMapping("/student")
public int insertStu(@RequestParam String id, @RequestParam String name, @RequestParam String birth, @RequestParam String sex) {
    MyStudent myStudent = new MyStudent();
    myStudent.setsId(id);
    myStudent.setsName(name);
    myStudent.setsBirth(birth);
    myStudent.setsSex(sex);
    return myStudentMapper.insert(myStudent);
}

3: @PutMapping、@PatchMapping

处理put和patch请求,传统的RequestMapping来编写应该是

@RequestMapping(value = "patch",method = RequestMethod.PUT/PATCH)

新方法可简写为:@PostMapping("patch")

两者都是更新,@PutMapping为全局更新,@PatchMapping是对put方式的一种补充,put是对整体的更新,patch是对局部的更新。例如:

/**
 * 局部更新用PatchMapping 全局更新用PutMapping
 * @param myStudent
 * @return
 */
@PatchMapping("/update")
public int updateById(MyStudent myStudent) {
    return myStudentMapper.updateByPrimaryKey(myStudent);
}

4:@DeleteMapping

处理delete请求,传统的RequestMapping来编写应该是
@RequestMapping(value = "path",method = RequestMethod.DELETE)

新方法可简写为:@DeleteMapping("path")

通常在删除数据的时候使用,例如:

/**
 * 根据ID删除一条数据
 *
 * @param id
 * @return
 */
@DeleteMapping("/delete/{id}")
public int deleteById(@PathVariable String id) {
    return myStudentMapper.deleteByPrimaryKey(id);
}

5:对于前端传值的时候注意:

对于json类型的数据(‘Content-Type’: ‘application/json’ ),需要使用@RequestBody接受,否则控制台会报错

对于其他类型的数据(‘Content-Type’: ‘application/x-www-form-urlencoded’),后台可以直接接受

最好使用json传值,因为null值在json中会被正常处理

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐