学习记录:RestFul风格

RestFul是一种风格不是一种技术

http://localhost:8080/SpringMvc_RestFul_war_exploded/hello?a=1&b=2

在传统的url中,我们数据的传递是通过以上的方法

而在RestFul中我们则为

localhost:8080/SpringMvc_RestFul_war_exploded/hello/1/2

在RestFul风格中,数据的传递更加简约,但是我们并不清楚 1 和 2到底是干什么的

我的理解是,更加促进了数据的安全性。

@Controller
public class Hello {
    @RequestMapping("/hello")
    public String hello(int a,int b,Model model)
    {
        int sum=a+b;
        model.addAttribute("msg","结果为:"+sum);
        return "hello";
    }
}

以下为RestFul代码的实现

我们需要添加PathVariable注解来进行实现 将对于的参数绑定到对应的URL模板之上

@Controller
public class Hello {
    @RequestMapping("/hello/{a}/{b}")
    public String hello(@PathVariable int a, @PathVariable int b, Model model)
    {
        int sum=a+b;
        model.addAttribute("msg","结果为:"+sum);
        return "hello";
    }
}

使用method属性指定请求类型

用于约束请求的类型,可以收窄请求范围。指定请求谓词的类型如GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE等

我们增加一个方法 将请求方法改为了POST 而默认的请求方法为GET

 @RequestMapping(value = "/hello2",method = {RequestMethod.POST})
    public String hello2(Model model)
    {
        model.addAttribute("msg","666");
        return "hello";
    }

此时我们进行请求就会报405错误

 而当我们将请求方法改为GET的时候便会正常访问

   @RequestMapping(value = "/hello2",method = {RequestMethod.GET})

当我们需要指定方法的时候,并不需要写这么繁琐的一大段代码,只需要写一个注释即可

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping

@GetMapping 是一个组合注解,平时使用的会比较多!

它所扮演的是 @RequestMapping(method =RequestMethod.GET) 的一个快捷方式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值