spring boot resource optional request param

To use an optional request parameter in Spring Boot, you can follow these steps:

  1. Define the Controller Method: Create a method in your controller class with the @RequestMapping or @GetMapping annotation. Make sure to specify the required path for the endpoint. For example:
@GetMapping("/example")
public ResponseEntity<String> exampleMethod(@RequestParam(required = false) String param) {
    // Method logic goes here
    return ResponseEntity.ok("Success");
}

In this example, the param parameter is marked as optional by setting the required attribute of the @RequestParam annotation to false.

  1. Handle the Optional Parameter: Inside the method, you can check if the parameter is present or not using the Optional class. For example:
@GetMapping("/example")
public ResponseEntity<String> exampleMethod(@RequestParam(required = false) Optional<String> param) {
    if (param.isPresent()) {
        // Parameter is present, handle it
        String value = param.get();
        // Handle the value
    } else {
        // Parameter is not present, handle it
    }
    return ResponseEntity.ok("Success");
}

In this example, the param parameter is wrapped in an Optional object. You can then use the isPresent() method to check if the parameter is present, and the get() method to retrieve its value.

  1. Use the Optional Parameter: After handling the optional parameter, you can use its value as needed in your method logic. For example, you can perform calculations, make database queries, or return a specific response based on the presence or absence of the parameter.

By following these steps, you can utilize optional request parameters in Spring Boot to create more flexible and customizable endpoints in your application.