一、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非必填
有时我们希望请求参数是可选的,即在请求中可以不包含该参数。这时我们可以使用RequestParam
的required
属性。当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
中的数组或集合将包含Tom
和Jerry
,最终返回Hello Tom,Jerry
。