Spring Controller 如何确定参数为必须提供

Spring MyController 如何确定参数为必须的。

备注

只需要在参数中确定 @RequestParam 注解 required 修改为 true 就可以了。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/endpoint")
    public String handleRequest(@RequestParam(name = "param", required = false) String param) {
        if (param == null) {
            return "Parameter 'param' is null";
        } else {
            return "Parameter 'param' is: " + param;
        }
    }
}

上面的代码显示的参数是必须的。

可选的方案是,我们可以在新版本中使用 Optional

如下面的代码:

import java.util.Optional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/endpoint")
    public String handleRequest(@RequestParam(name = "param") Optional<String> param) {
        return param.orElse("Parameter 'param' is not present");
    }
}

我们把代码中对参数的要求修改为: Optional

下面的代码显示了 GTP 的回答。

默认情况下是必须要向参数提供内容。

2 Likes
Search

Found 0 results for 'Spring MyController 参数必须 status:public'

It seems there are no topics directly discussing how to ensure parameters are required in a Spring MyController on this forum. However, I can provide some guidance on the topic.

To specify that a parameter is required in a Spring @Controller, you generally use the @RequestParam or @PathVariable annotations. By default, the required attribute for these annotations is set to true, which means they are mandatory. Here’s how you can ensure that parameters are required:

  1. Using @RequestParam:
@GetMapping("/example")
public String example(@RequestParam(required = true) String param) {
    // Your code here
}
  1. Using @PathVariable:
@GetMapping("/example/{param}")
public String example(@PathVariable String param) {
    // Your code here
}

In these examples, the @RequestParam is explicitly set as required (though this is the default behavior), and @PathVariable is inherently required.

If this doesn’t answer your question or you need further assistance, you might want to consider rephrasing your search query or specifying more details, such as versions or specific use cases, so I can help more effectively!