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

原文地址:https://www.cnblogs.com/doumenwangjian/p/14411979.html