RequestParam非必填详解

发布时间:2023-05-17

一、RequestParam概述

RequestParam是Spring MVC中常用的注解之一,用于将请求参数映射到控制器方法的参数上。在默认情况下,RequestParam会将请求参数与控制器方法参数名匹配,并将请求参数的值赋值给控制器方法参数。如下面的代码所示:

@GetMapping("/hello")
public String sayHello(@RequestParam String name) {
    return "Hello " + name;
}

当我们访问http://localhost:8080/hello?name=Tom时,控制器方法sayHello中的参数name将被自动映射到请求参数name的值,最终返回Hello Tom

二、RequestParam非必填

有时我们希望请求参数是可选的,即在请求中可以不包含该参数。这时我们可以使用RequestParamrequired属性。当required属性设置为true时,如果请求中没有该参数,则会抛出MissingServletRequestParameterException异常。当required属性设置为false时,如果请求中没有该参数,则控制器方法参数的值将为null

@GetMapping("/hello")
public String sayHello(@RequestParam(required = false) String name) {
    if(name == null) {
        return "Hello World";
    } else {
        return "Hello " + name;
    }
}

当我们访问http://localhost:8080/hello时,控制器方法sayHello中的参数name将为null,最终返回Hello World。当我们访问http://localhost:8080/hello?name=Tom时,控制器方法sayHello中的参数name将被赋值为Tom,最终返回Hello Tom

三、RequestParam默认值

除了将required属性设置为false之外,RequestParam还可以通过设置defaultValue属性来指定请求参数的默认值。当请求中没有该参数时,控制器方法参数的值将为defaultValue的值。

@GetMapping("/hello")
public String sayHello(@RequestParam(defaultValue = "World") String name) {
    return "Hello " + name;
}

当我们访问http://localhost:8080/hello时,控制器方法sayHello中的参数name将为World,最终返回Hello World。当我们访问http://localhost:8080/hello?name=Tom时,控制器方法sayHello中的参数name将被赋值为Tom,最终返回Hello Tom

四、RequestParam多个参数

RequestParam还支持映射多个参数,可以使用数组或集合作为控制器方法参数。如果请求中没有包含该参数,则数组或集合的长度为0或空集合。

@GetMapping("/hello")
public String sayHello(@RequestParam String[] names) {
    if(names.length == 0) {
        return "Hello World";
    } else {
        return "Hello " + String.join(",", names);
    }
}
@GetMapping("/hello")
public String sayHello(@RequestParam List<String> names) {
    if(names.isEmpty()) {
        return "Hello World";
    } else {
        return "Hello " + String.join(",", names);
    }
}

当我们访问http://localhost:8080/hello时,控制器方法sayHello中的数组或集合将为空,最终返回Hello World。当我们访问http://localhost:8080/hello?names=Tom&names=Jerry时,控制器方法sayHello中的数组或集合将包含TomJerry,最终返回Hello Tom,Jerry