3

Say I have an endpoint that accepts requests as follows:

GET https://my.website.com/products?expired

OR

GET https://my.website.com/products

The method I would expect to work:

@GetMapping
public List<Product> products(@RequestParam(value = "expired", required=false) boolean expired) {
   //Implementation details
}

This however, will return a Bad Request 400 response.

I know I would get this to work by sending the expired requestParam as expired=true, but I'd like for this to work similar to HTML boolean attributes where the mere presence of a request param represents true and its absence represents false

Robin-Hoodie
  • 4,886
  • 4
  • 30
  • 63

2 Answers2

4

Use Boolean instead of boolean - the problem you have is that you are trying to unbox null value to the primitive boolean which operation causes NullpointerException and further Bad Request 400 response

public List<Product> products(@RequestParam(value = "expired", required=false) Boolean expired)

Here you can read something more about unboxing Boolean

m.antkowicz
  • 13,268
  • 18
  • 37
  • 1
    Sending a `GET` request to `https://my.website.com/products?expired` will evaluate the value of the `click` variable to `null` – Robin-Hoodie Nov 21 '18 at 21:06
  • 1
    @Robin-Hoodie That;'s right. So you need to treat `null` the same was `false` to achieve what you want. – Erwin Bolwidt Nov 21 '18 at 21:21
  • 2
    That doesn't satisfy my question though, the presence of the `expired` request param should be enough to have it evaluate to `true` – Robin-Hoodie Nov 21 '18 at 21:22
  • Ok I see - I believe that what you're trying to achieve is not possible in an easy way and even if you would do this it would be misleading. You should create specific endpoint like `website.com/products/expired` for your purpose or just keep on setting specific `true/false` value – m.antkowicz Nov 22 '18 at 08:05
1

I wonder if you'll have to implement two methods, one with and one without the param, the second with it required (and probably Boolean non-primitive, as the other answer suggests).

(Then just call a common method from both.)

dbreaux
  • 4,982
  • 1
  • 25
  • 64