【Java】springboot @RequestParam 如何使用 ?

Spring Boot 中的 @RequestParam 注解用于从 URL 中获取参数值,常用于 GET 请求中传递参数值。使用该注解时,需要指定参数名称和参数类型。

以下是一些示例:

  1. 获取单个参数 @GetMapping("/example") public ResponseEntity<?> exampleMethod(@RequestParam String name) { // 处理请求 } 上面的代码定义了一个 GET 方法,并在方法签名中添加了 @RequestParam 注解,其中参数 name 为必需的。这意味着如果在 URL 中未提供参数,则会抛出异常。如果参数存在,请求将被成功处理,并且将参数值作为字符串传递到 exampleMethod 方法中的 name 参数中进行处理。
  2. 获取可选参数 @GetMapping("/example") public ResponseEntity<?> exampleMethod(@RequestParam(required = false) String name) { // 处理请求 } 增加 @RequestParam 的 required 属性,并设置为 false,表示该参数是可选的。如果在 URL 中找不到该参数,则会将其设置为 null 而不是抛出异常。
  3. 设置默认值 @GetMapping("/example") public ResponseEntity<?> exampleMethod(@RequestParam(defaultValue = "default") String name) { // 处理请求 } 使用 defaultValue 属性可以为未提供值的参数设置默认值。如果参数在 URL 中不存在,默认值将作为参数值传递到 exampleMethod 方法中的 name 参数中进行处理。
  4. 使用自定义类型 @GetMapping("/example") public ResponseEntity<?> exampleMethod(@RequestParam MyCustomType myCustomType) { // 处理请求 } 使用 @RequestParam 注解时,参数类型不一定要设置为基本数据类型或者字符串。如果在 Spring 应用程序上下文中存在适当的转换器,则可以将参数转换为任何支持的类型。这里示例中,使用了一个自定义类型 MyCustomType,Spring Boot 会尝试从 URL 中获取相应的参数,并将其转换为 MyCustomType 对象传递给 exampleMethod 方法进行处理。

以上就是 @RequestParam 注解的示例用法。如果您需要更多的操作和属性参数,建议查看官方文档以获取更多详细信息。

经验分享 程序员 微信小程序 职场和发展