我使用Spring Boot。
在 REST 控制器中,当我们使用@RequestParam
注释将字符串参数的默认值设置为null
时,有没有办法?
Spring的@RequestParam
注释支持:
required
defaultValue
所以,像这样的映射...
@GetMapping(value = "/{first}")
public ResponseEntity<String> doSomething(@PathVariable int first, @RequestParam(required = false) String foo) {
// ...
}
。定义了一个名为foo
的请求参数,它是可选的,如果调用者不传递此参数,Spring 将为其提供null
(因为null
是 String 对象的单元化状态)。
不需要将null
设置为String
的初始值,因为默认值已经null
String
,但其他值可以在@RequestParam
注释中使用defaultValue
设置。
请在下面找到使用defaultValue
的示例:
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/name")
String getName(@RequestParam(value = "person", defaultValue = "John") String personName) {
return "Required element of request param";
}
}