您的当前位置:首页正文

ResTful风格的Url

2024-11-08 来源:个人技术集锦

7.1 RESTful简介

RESTful就是一个资源定位及资源操作的风格。不是标准也不
是协议,只是一种风格。基于这个风格设计的软件可以更简
洁,更有层次。

往常的传参方式: 

http://localhost:8080/springmvc02/user/queryUserById?id= 1 查询
http://localhost:8080/springmvc02/user/saveUser新增
http://localhost:8080/springmvc02/user/updateUser 更新
http://localhost:8080/springmvc02/user/deleteUserById?id=1 删除

使用RESTful操作资源:使用URL+请求方式确定具体的动作

使用Restful操作:

http://localhost:8080/springmvc02/user/1  查询,GET
http://localhost:8080/springmvc02/user    新增,POST
http://localhost:8080/springmvc02/user    更新,PUT 
http://localhost:8080/springmvc02/user/1  删除,DELETE

RESTFul风格好处:

查询 /emp/editEmp?empId=2 /emp/2      请求方式:GET
保存 /emp/saveEmp /emp                请求方式:POST
更新 /emp/updateEmp /emp              请求方式:PUT
删除 /emp/removeEmp?empId=2 /emp/2    请求方式:DELETE

7.2 RESTFul案例

@Controller
public class EmpController {
//根据ID查询
@RequestMapping(value ="/emp/{empId}",method = RequestMethod.GET)
@ResponseBody
public Result findById(@PathVariable("empId") Integer empId){
Result result=new Result(20001,"查询成功",empId);
return result;
}

//查询所有
@RequestMapping(value = "/emp",method =RequestMethod.GET)
@ResponseBody
public Result findAll(){
Result result=new Result(20002,"查询成功",null);
return result;
}

//保存
@RequestMapping(value = "/emp",method = RequestMethod.POST)
@ResponseBody
public Result save(@RequestBody Emp emp){
Result result=new Result(20003,"保存成功",emp);
return result;
}

//删除
@RequestMapping(value ="/emp/{empId}",method = RequestMethod.DELETE)
@ResponseBody
public Result delete(@PathVariable("empId")Integer empId){
Result result=new Result(20004,"删除成功",empId);
return result;
}

//修改
@RequestMapping(value = "/emp",method = RequestMethod.PUT)
@ResponseBody
public Result update(@RequestBody Emp emp){
Result result=new Result(20005,"修改成功",emp);
return result;
}
}

7.3 注解优化

@RestController //这一个注解相当于同时写了@Controller+@ResponseBody
@RequestMapping("/emp")
public class EmpController {
//根据ID查询
@GetMapping("/{empId}")
@ResponseBody
public Result findById(@PathVariable("empId") Integer empId){
Result result=new Result(20001,"查询成功",empId);
return result;
}
//查询所有
@GetMapping
@ResponseBody
public Result findAll(){
Result result=new Result(20002,"查询成功",null);
return result;
}
//保存
@PostMapping
@ResponseBody
public Result save(@RequestBody Emp emp){
Result result=new Result(20003,"保存成功",emp);
return result;
}
//删除
@DeleteMapping("/{empId}")
@ResponseBody
public Result delete(@PathVariable("empId")
Integer empId){
Result result=new Result(20004,"删除成功",empId);
return result;
}
//修改
@PutMapping
@ResponseBody
public Result update(@RequestBody Emp emp){
Result result=new Result(20005,"修改成功",emp);
return result;
}
}

 

Top