What's the difference between QueryParam and MatrixParam in JAX-RS?

jiafu picture jiafu · Apr 17, 2012 · Viewed 34.3k times · Source

What's the difference between the JAX-RS @QueryParam and @MatrixParam? From the documents.The queryparam and matrixparam both can location one resource in special condition. So what's the use case difference?

ps:

Queryparam:

url ? key=value;

Matrixparam

url; key=value;

Answer

Hardik Patel picture Hardik Patel · Oct 4, 2017

The @MatrixParam annotation will apply to particular Resource present in URL and @QueryParam will apply to whole Request URL.

Take a example of any Supermarket, If you want all fruits which will be satisfied multiple conditions like type=fruits and price range starts from 300 and list out matching 10 fruits, you can go for below API Design,

http://dev.brandstore.com/inventory/grocery;type=fruits/price;range=300/?limit=10

In above example, first Matrix Param type=fruits is applying to only grocery resource same range=300 is applying to only price resource but Query Param for pagination limit=10 is applying to whole Request URL. And yes, If only query parameters were used, you would end up with parameters like "grocery_type" and "grocery_price" and you would lose the clarity added by the locality of the parameters within the request.