SpringBoot 获取Get请求参数方式

本文详细介绍了SpringBoot中如何通过不同方式处理GET请求的参数,包括路径变量、查询参数、RequestParam、RequestParamMap、HttpServletRequest、对象绑定以及构造函数接收参数等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot 获取Get请求参数方式

参数直接在路径中

例如:
http://localhost:8080/hello/john
获取参数 :
@GetMapping(“/hello”)
public String hello(@PathVariable(“name”)String name)

参数跟在 ? 号后面

例如:
http://localhost:8080/hello2?name=john&age=18
获取参数:
@GetMapping(“/hello2”)
public String hello2(@RequestParam(“name”) String name,@RequestParam(“age”) Integer age)

参数没有传递的情况

例如:
http://localhost:8080/hello3
获取参数:
@GetMapping(“/hello3”)
public String hello3(
@RequestParam(value = “name”,required = false ) String name ,
@RequestParam(value = “age”,defaultValue = 18) Integer age)

注:这里name非必填,age给了一个默认值

使用 map 来接收参数

例如:
http://172.16.23.243:48090/hello4?name=John&age=18
获取参数:
@GetMapping(“/hello4”)
public String hello4(
@RequestParam Map<String,Object> params)

接收一个数组

例如:
http://172.16.23.243:48090/hello5?name=John&name=Amy
获取参数:
@GetMapping(“/hello5”)
public String hello5(
@RequestParam(“name”) String[] list
)

接收所有的参数

例如:
http://172.16.23.243:48090/hello5?name=John&age=18
获取参数:
@GetMapping(“/hello6”)
public String hello6(HttpServletRequest request)

使用对象来接收参数

例如:
http://172.16.23.243:48090/hello7?name=John&age=18
获取参数:
@GetMapping(“/hello7”)
public String hello7(User user)
User类:
package com.example.demo.controller;

public class User {
private String name;
private Integer age;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Integer getAge() {
    return age;
}

public void setAge(Integer age) {
    this.age = age;
}

}

指定前缀的方式接收参数

例如:
http://172.16.23.243:48090/hello8?u.name=John&age=18
获取参数:
@GetMapping(“/hello8”)
public String hello(@ModelAttribute(“u”) User user) {
return “name:” + user.getName() + “
age:” + user.getAge();
}

@InitBinder("u")
private void initBinder(WebDataBinder binder) {
    binder.setFieldDefaultPrefix("u.");
}

注: 除了在 Controller 里单独定义预处理方法外,我们还可以通过 @ControllerAdvice 结合 @InitBinder 来定义全局的参数预处理方法,方便各个 Controller 使用。

构造多个对象接收参数

例如:
http://172.16.23.243:48090/hello9?name=John&age=18&phone=11621055255
获取参数:
@GetMapping(“/hello9”)
public String hello9(User user,Phone phone){
return “name:” + user.getName() + “
age:” + user.getAge() + “
phone:” + phone.getPhone();
}
另外一个对象类:

public class Phone {
private String phone;
public void setPhone(String phone){
this.phone=phone;
}
public String getPhone(){
return phone;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值