Check if a parameter is specified or not into the URL

Royce :

It is possible to test if a parameter exists or not into an URL with Spring?

Below, my current code, but maybe that if(status == null) is a bit dirty right?

@GetMapping
public ResponseEntity<?> getAllTasks(@RequestParam(value = "status", required = false) Integer status) {
    if(status == null) {
        return new ResponseEntity<>(this.taskResource.findAll(), HttpStatus.OK);
    }
    return new ResponseEntity<>(this.tacheResource.getTachesByEtat(status), HttpStatus.OK);
}

The method getAllTasks() will be call in different cases:

  • localhost:8080/tasks
  • localhost:8080/tasks/?status=...

That's why I try to find another way to do this test.

Can you help me ?

Thanks.

Ayrton :

Depending on your Java version, you can use Optional and isPresent() (but you'll have to get the value from your status variable using status.get()):

@GetMapping
public ResponseEntity<?> getAllTasks(@RequestParam("status") Optional<Integer> status) {
    if(!status.isPresent()) {
        return new ResponseEntity<>(this.taskResource.findAll(), HttpStatus.OK);
    }
    return new ResponseEntity<>(this.tacheResource.getTachesByEtat(status.get()), HttpStatus.OK);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=143842&siteId=1