springboot的RESTFull开发

13 篇文章 0 订阅
6 篇文章 0 订阅

rest  demo下载地址:https://download.csdn.net/download/yanhhuan/13101768

 

@PathVariable

获取url中的数据

该注解是实现RESTFull最主要的一个注解

eg:

package com.example.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * restfull
 */
@RestController
public class RESTFullController {
    //访问地址http://localhost:8080//boot/restfullstudent/id/status
    @RequestMapping("/boot/restfullstudent/{id}/{status}")
    public Object  restfullstudent(@PathVariable("id") Integer id,@PathVariable("status") Integer status){
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("id",id);
        map.put("status",status);
        return map;
    }
}

放参数的位置也可以改变

//访问地址http://localhost:8080//boot/id/restfullstudent/status
@RequestMapping("/boot/{id}/restfullstudent/{status}")
public Object  restfullstudent01(@PathVariable("id") Integer id,@PathVariable("status") Integer status){
    Map<String,Object> map=new HashMap<String,Object>();
    map.put("id",id);
    map.put("status",status);
    return map;
}

注:同一个类中如果存在两个方法,路径中的http一致

restfull访问参数位置是不一致的

那参数位置可以不一致但是顺序要一致,如果顺序不一致方法会报错

eg:

@RequestMapping("/boot/restfullstudent/{id}/{status}")
@RequestMapping("/boot/{id}/restfullstudent/{status}")

这样在同一个类中是可以的

 

但是

@RequestMapping("/boot/restfullstudent/{id}/{status}")
@RequestMapping("/boot/{status}/restfullstudent/{id}")

这样在同一个类中是不可以的

解决冲突的2个方法:

1.路径改为不一样的

@RequestMapping("/boot/restfullstudent/{id}/{status}")
@RequestMapping("/boot/{status}/restfullstudentsn/{id}")

2.修改请求方式

eg:第二个方法改为

@PostMapping

 

 

RESTFull原则:

1.增post请求,删delete请求,改put请求,查get请求

@PostMapping

@DeleteMapping

@PutMapping

@GetMapping

2.请求路径不要出现动词,比如查询订单:/boot/order/1/1021 (正确),/boot/queryOrder/1/1021 (不建议)

3.分页、排序等操作,不需要采用斜杠传参数,订单列表接口:/boot/orders?p=1&sort=desc,传的参数不是数据库的字段,可以不采用斜杠

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值