6.ResuFul风格

6.ResuFul风格

一种资源定位与资源操作的风格,更加简洁、更加有层次,对于缓存机制更友好。

6.1 与正常风格比较的不同

正常风格 : localhost:8080/method?name=陆源东

RestFul风格 : localhost:8080/method/name/陆源东

6.2 实例

传统资源操作方式

  • post
  • get

通过不同的参数实现不同的功能

http://127.0.0.1/item/queryItem.action?id=1 GET方法查询

http://127.0.0.1/item/saveItem.action POST方法新增

http://127.0.0.1/item/updateItem.action POST方法更新

http://127.0.0.1/item/deleteItem.action?id=1 POST方法删除

**使用RestFul风格操作 **: 可以通过不同的请求方式实现不同的效果

http://127.0.0.1/item/1 GET方法查询

http://127.0.0.1/item POST方法新增

http://127.0.0.1/item PUT方法新增

http://127.0.0.1/item/1 DELETE方法删除

6.3 RestFul风格实现

原方式

@Controller
public class TestController{
    @RequestMapping("/test")
    //前端传递通过普通风格传递 a与b
    public String test(int a,int b,Model model) {
        //封装数据
        int res = a+b;
        model.addAttribute("msg",res);
        return "hello";
    }
}
http://localhost:8080/test?a=1&b=2  //传递参数 a=1 , b=2  , 页面返回3

RestFul风格实现

@注解PathVariable : 让方法参数的值对应绑定到一个URL模板变量上

@Controller
public class TestController{
    //模板URL ,会直接通过 / 的形式绑定a与b
    @RequestMapping("/test/{a}/{b}")  
    //参数类型也可以为String、float、double等
    public String test(@PathVariable int a,@PathVariable int b, Model model) {
        //封装数据
        int res = a+b;
        model.addAttribute("msg",res);
        return "hello";
    }
}
http://localhost:8080/test/1/2 

**RequestMethod[] 参数 **:限定请求的类型

@Controller
public class TestController{
    //模板URL ,会直接通过 / 的形式绑定a与b
    @RequestMapping(value = "/test/{a}/{b}",method= RequestMethod.DELETE) //通过参数的方式限定方法
    public String test(@PathVariable int a,@PathVariable String b, Model model) {
        //封装数据
        String res = a+b;
        model.addAttribute("msg",res);
        return "hello";
    }
}
@Controller
public class TestController{
    //模板URL ,会直接通过 / 的形式绑定a与b
    @GetMapping("/test/{a}/{b}")  //通过注解的方式限定提交方法
    public String test(@PathVariable int a,@PathVariable String b, Model model) {
        //封装数据
        String res = a+b;
        model.addAttribute("msg",res);
        return "hello";
    }
}

实现相同路径不同功能(通过不同请求类型)

@Controller
public class TestController{
    //模板URL ,会直接通过 / 的形式绑定a与b
    @GetMapping("/test/{a}/{b}")  //Get提交方法进入test
    public String test(@PathVariable int a,@PathVariable String b, Model model) {
        //封装数据
        String res = a+b;
        model.addAttribute("msg",res);
        return "hello";
    }
    @PostMapping("/test/{a}/{b}")  //Post提交方法进入test1
    public String test1(@PathVariable int a,@PathVariable String b, Model model) {
        //封装数据
        String res = a+b;
        model.addAttribute("msg",res);
        return "hello1";
    }
    
}

6.4 ResuFul风格的优点

  1. 安全,不暴露变量
  2. 简洁高效,支持缓存
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值