1

I have a request like http://example.com?value=xyz and i have to write GET for this. The requirement is, when i have a value, the response has to be for hat particular record "xyz" from database. But if the request ishttp://example.com i.e without value, it has to retrieve all values from the DB.

So for achieveing this, I have (@RequestParam(value= "name", required=false)String name) in my request. i.e marked the value as optional

But the problem is when my request is http://example.com?value=i.e without a value, i must throw 'request is invalid' as error and not retrieve all the values from the DB. But in my case when i mark the param as optional, it retrieves all records from DB.

Is there a way to do validations for optional request parameters?

gayu312
  • 61
  • 2
  • 7
  • Possible duplicate of [Optional @Pathvariable in REST controller spring 4](https://stackoverflow.com/questions/47567364/optional-pathvariable-in-rest-controller-spring-4) – Mehraj Malik Mar 06 '18 at 04:15

2 Answers2

0

If you want to stick to the query string style, you can add two separate handlers One for http://example.com And other with required=true for http://example.com?value=xyz. And you still reuse most of your code with separate common private method.

However,

If you can change your url pattern to use path variables, it becomes more readable and cleaner.

@GetMapping(path={"/", "/value/{value}")
public void method(@PathVariable(name = "value", required = false) String value){
  // Your code
}

And then you can query this endpoint like

  • http://example.com
  • http://example.com/value/xyz
Amit Phaltankar
  • 3,341
  • 2
  • 20
  • 37
0

You can check the query string in your controller, that should work:

if (request.getQueryString() != null) {
   if (value.isPresent() || request.getQueryString().contains("value")){
    if (!value.isPresent()){
        // Throw your error
    }
  }
}

The code above will first check if value is present or the url/query string contains the word "value" if either are true it will hit the next if statement. Then you can check if value is not present. If it not it means someone sent you http://example.com?value= and you can throw an error.

Aaron
  • 1,361
  • 1
  • 13
  • 30