Spring Framework — Most of you don’t know how to use query parameter(s)!!

Spring framework is well designed and works like magic.


Yes, magic!

That’s why only a few people know about it. (If you already know this, you are AWESOME!)

OK, start!

GET /rooms
GET /rooms/:id
POST /rooms
PUT /rooms/:id
PATCH /rooms/:id
DELETE /rooms/:id

If you ask you to design above endpoint, it would be easy, right?

how about these

GET /rooms?popular={number}

GET /rooms?stars={number}

GET /rooms?popular={number}&stars={number}

popular indicates the most viewed rooms, popular=5 means list top 5 rooms

stars uses to filter the rooms which have star more than the input
eg. stars 3.5 will show only rooms where it has stars ≥ 3.5

Which one will you write?

Stupid code using if else

The first one will cause a lot of problem if you have more than two parameter!!, the if-else condition will be longer and more complex, then the next developer will blame your whole family.

You can overload endpoint using params attribute, this will make your controller beautiful.

Next post I will post about more complex query parameters, Cheers!