05-RestFul风格讲解

本文深入探讨了Restful风格的API设计,通过实例展示了如何使用Spring框架的注解实现GET和POST请求的方法映射。文章指出,Restful风格使得URL更加直观,参数传递更加简洁,易于理解和实现缓存。同时,提供了代码示例解释了如何使用`@GetMapping`和`@PostMapping`注解处理不同的HTTP请求方法。
摘要由CSDN通过智能技术生成

RestFul风格讲解

Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

/*
普通传参:   http://localhost:8080/add?a=1&b=2

restful风格传参:http://localhost:8080/add/a/b
http://localhost:8080/add/1/2

*/

代码理解

package com.kuang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
public class RestFulController {


    @GetMapping("/add/{a}/{b}")
    public String test1(@PathVariable int a,@PathVariable int b, Model model){
        int res=a+b;
        model.addAttribute("msg","结果为"+res);
        return  "test";
    }
}

/*
@PathVariable      RestFul要用这个

@GetMapping("/add/{a}/{b}")  相当于 @RequestMapping(name="/add/{a}/{b}",method = RequestMethod.GET)
还有其他别名 value,path
@RequestMapping(value="/add/{a}/{b}",method = RequestMethod.GET)
@RequestMapping(path="/add/{a}/{b}",method = RequestMethod.GET)

当然这些很少用!都是用@GetMapping("/add/{a}/{b}") 这种组合注解的

类似的还有以下这个
   @DeleteMapping() 
   @PostMapping() 只能用post请求
    
 */
@Controller
public class RestFulController {


    @GetMapping("/add/{a}/{b}")
    public String test1(@PathVariable int a,@PathVariable int b, Model model){
        int res=a+b;
        model.addAttribute("msg","结果1为"+res);
        return  "test";
    }
    
        @PostMapping("/add/{a}/{b}")
    public String test2(@PathVariable int a,@PathVariable int b, Model model){
        int res=a+b;
        model.addAttribute("msg","结果2为"+res);
        return  "test";
    }
}

//地址可以一样,提交方式不同,走的方法不同
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值