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;
}
}