为批注中的默认值分配 null @RequestParam



我使用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的初始值,因为默认值已经nullString,但其他值可以在@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";  
}  
}

最新更新