spring boot常见get 、post请求参数处理

spring boot 常见http get ,post请求参数处理

 
 在定义一个Rest接口时通常会利用GET、POST、PUT、DELETE来实现数据的增删改查;这几种方式有的需要传递参数,后台开发人员必须对接收到的参数进行参数验证来确保程序的健壮性
GET
一般用于查询数据,采用明文进行传输,一般用来获取一些无关用户信息的数据
POST
一般用于插入数据
PUT
一般用于数据更新
DELETE
一般用于数据删除
一般都是进行逻辑删除(即:仅仅改变记录的状态,而并非真正的删除数据)

@PathVaribale 获取url中的数据
@RequestParam 获取请求参数的值
@GetMapping 组合注解,是 @RequestMapping(method = RequestMethod.GET) 的缩写
@RequestBody 利用一个对象去获取前端传过来的数据

1. PathVaribale 获取url路径的数据

请求URL:
localhost:8080/hello/id 获取id值

实现代码如下:

@RestController
public class HelloController {
    @RequestMapping(value="/hello/{id}/{name}",method= RequestMethod.GET)
    public String sayHello(@PathVariable("id") Integer id,@PathVariable("name") String name){
        return "id:"+id+" name:"+name;
    }
}

在浏览器中 输入地址:

localhost:8080/hello/100/hello

输出:
id:81name:hello

 

2. RequestParam 获取请求参数的值

获取url参数值,默认方式,需要方法参数名称和url参数保持一致
localhost:8080/hello?id=1000

@RestController
public class HelloController {
    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(@RequestParam Integer id){
        return "id:"+id;
    }
}

输出:
id:100

url中有多个参数时,如:
localhost:8080/hello?id=98&&name=helloworld
具体代码如下:

@RestController
public class HelloController {
    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(@RequestParam Integer id,@RequestParam String name){
        return "id:"+id+ " name:"+name;
    }
}

获取url参数值,执行参数名称方式
localhost:8080/hello?userId=1000

@RestController
public class HelloController {
    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(@RequestParam("userId") Integer id){
        return "id:"+id;
    }
}

输出:
id:100

注意

不输入id的具体值,此时返回的结果为null。具体测试结果如下:
id:null
不输入id参数,则会报如下错误:
whitelable Error Page错误

 

3. GET参数校验

用法:不输入id时,使用默认值
具体代码如下:
localhost:8080/hello

@RestController
public class HelloController {
    @RequestMapping(value="/hello",method= RequestMethod.GET)
    //required=false 表示url中可以无id参数,此时就使用默认参数
    public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){
        return "id:"+id;
    }
}

输出
id:1

参考:https://blog.csdn.net/yunfeng482/article/details/79756233

 

posted @   王短腿  阅读(1396)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示