SpringBoot 请求参数

@PathVariable 接收路径参数

带路径占位符的 URL 是 Spring3.0 新增功能,通过@PathVariable可以将 URL 中占位符参数绑定到控制器的处理方法入参中。

属性
类型
是否必要
说明

name

String

指定请求参数绑定的名称,如果省略则绑定同名参数

value

String

name属性性的别名

required

boolean

指示参数是否必须绑定

必须路径变量

路径变量是必须的,否则会匹配到404请求。

/**
 * http://localhost:8080/users/1
 */
@GetMapping("/users/{id}")
public String users(@PathVariable("id") Integer id) {
    return "Hello, World!";
}

在这里,Spring 会尝试将路径变量id绑定到id参数上,例如发送/user/1,此时id的值会被绑定为1。

可选路径变量

@GetMapping可以同时匹配到多个请求路径时,我们可以通过设置require=false来表示当前路径变量为可选值。如果设置required=true时,,访问/books时会抛出500错误。

/**
 * http://localhost:8080/books/1
 * http://localhost:8080/books
 */
@GetMapping(value = {"/books/{id}", "/books"})
public String books(@PathVariable(value = "id", required = false) Integer id) {
    return "Hello, World!";
}

以下实现展示了 Spring 4.1 以及JDK 8 的可选类如何提供另一种使用可选路径变量的方法:

@GetMapping(value = {"/articles/{id}", "/articles"})
public String articles(@PathVariable Optional<Integer> id) {
    return "Hello, World!";
}

在这里,Spring 创建了Optional<Integer> 实例, 使用参数id来保存id的值。如果id存在,id形参将包装其值,否则,id 将包装 null 值。然后,我们可以使用OptionalisPresent() get() orElse()方法来处理该值。

接收时间参数

在使用路径变量来接收时间参数时,需要制定接受的时间格式类型

/**
 * http://localhost:8080/api/date/2022-11-21 12:34:45
 */
@GetMapping(value = "/date/{dateTime}")
public Date fetchResult(@PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date dateTime) {
    return dateTime;
}


/**
 * (new Date()).toISOString() => 2021-08-31T07:44:45.000Z
 * http://localhost:8080/api/date/2021-08-31T07:44:45.000Z
 */
@GetMapping(value = "/date/{dateTime}")
public Date fetchResult(@PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date dateTime) {
    return dateTime;
}

@MatrixVariable 接收矩阵变量

MatrixVariable注解拓展了URL请求地址的功能。使用@Matrixvariable注解时多个变量可以使用;(分号)分隔,该注解允许开发者进行多条件组合査询。

属性
类型
是否必要
说明

name

String

指定请求参数绑定的名称,如果省略则绑定同名参数

value

String

name属性的别名

pathVar

String

matrix variable所在路径的url path变量的名称

required

boolean

指示参数是否必须绑定

defaultValue

String

如果没有传递参数而使用的默认值

/**
 * http://localhost:8080/api/car/1;brand=jack;color=23
 */
@GetMapping(value = "/car/{id}")
public String car(
        @PathVariable("id") Long id,
        @MatrixVariable(value = "brand", pathVar = "id") String brand,
        @MatrixVariable(value = "color", pathVar = "id") String color) {
    return brand + color;
}

GET 请求参数接收

实体类接收

通过实体类接收GET请求参数时,要求参数名称保持一致。

@Data
public class User {
    private String name;
    private Integer age;
}
/**
 * http://localhost:8080/user?name=zs&age=20
 */
@GetMapping("/user")
public User queryUser(User user) {
    return user;
}

@RequestParam 接收

属性
类型
是否必要
说明

name

String

指定请求参数绑定的名称

value

String

name属性的别名

required

boolean

指定参数是否必须绑定

dafaultValue

String

如果没有传递参数而使用的默认值

/**
 * http://localhost:8080/user?username=zs&pageNumber=1&pageSize=10
 */
@GetMapping("/user")
public String queryUser(
        @RequestParam(value = "username", required = false, defaultValue = "") String username,
        @RequestParam(value = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,
        @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize
) {
    return null;
}

@RequestParam注解用于将请求参数绑定到方法参数上,他有以下三个常用参数:

  1. value:(或name)用于指定要绑定的请求参数名称,这是唯一必须的参数。

@GetMapping("/user")
public String queryUser(@RequestParam(value = "username") String name) {
    return null;
}
// 或者简便写法
@GetMapping("/user")
public String queryUser(@RequestParam("username") String name) {
    return null;
}
  1. required:布尔值,用于指定参数是否必须,默认值是true。

@RequestParam(value = "paramtterName", required = false)
  1. defaultValue:用于指定在请求中未提供参数值时的默认值。

@RequestParam(value = "paramtterName", required = false, defaultValue = "defaultVal")

通过这种方式接收请求参数时,如果请求参数和方法参数名称一致时,@RequestParam注解可以省略。

/**
 * http://localhost:8080/user?name=zs&age=20
 */
@GetMapping("/user")
public String queryUser(String name, String age) {
    return null;
}

使用Map接收

在使用Map接受请求参数时,@RequestParam必须添加,用于将请求参数注入到map中。

@GetMapping("/user")
public User queryUser(@RequestParam Map<String, > map) {
    // .......
}

接收数组参数

/**
 * http://localhost:8080/user?name=zs&name=ls
 */
@GetMapping("/array")
public Integer[] queryUsers(Integer[] names) {
    return null;
}

接收时间参数

@DateTimeFormat设置接收参数格式,@JsonFormat设置响应时间格式

@Data
public class DateDto {
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime startDateTime;

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate endDateTime;
}
/**
 * http://localhost:8080/api/users?startDateTime=2022-12-12 12:33:21&endDateTime=2022-12-12
 */
@GetMapping(value = "/users")
public String users(DateDto dateDto) {
    System.out.println(dateDto);
    // DateDto(startDateTime=2022-12-12T12:12:12, endDateTime=2022-12-12)
    return null;
}

如果要单个接收的话,使用下面的方式,对时间参数使用@DateTimeFormat进行注解。

@GetMapping(value = "/user")
public String fetchResult(
        @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDateTime,
        @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endDateTime
) {
    return null;
}

全局配置时间类型参数的格式。

spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
  mvc:
    format: 
      date: yyyy-MM-dd
      date-time: yyyy-MM-dd HH:mm:ss
      time: HH:mm:ss

POST 请求参数接收

用实体类接收JSON数据

@PostMapping("/user")
public String createUser(@RequestBody UserDto userDto) {
    // ...
}

用Map接收application/x-www-form-urlencoded格式的数据

@PostMapping("/user")
public User createUser(@RequestParam Map<String, String> map) {
    String name = map.get("name");
    int age = Integer.parseInt(map.get("age"));
    return new User(name, age)
}

用Map来接收json数据

@PostMapping("/user")
public User createUser(@RequestBody Map<String, String> map) {
    String name = map.get("name");
    int age = Integer.parseInt(map.get("age"));
    return new User(name, age)
}

@RequestBody注解用于将请求体中的json字符串转化为对象属性,并注入到map

@RequestHeader

最后更新于

这有帮助吗?