一、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 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”。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/248368.html