What's the difference between QueryParam and M

2020-02-23 06:30发布

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;

标签: java jax-rs
2条回答
唯我独甜
2楼-- · 2020-02-23 07:11

As stated in this Oracle documentation:

The @PathParam and the other parameter-based annotations, @MatrixParam, @HeaderParam, @CookieParam, @FormParam obey the same rules as @QueryParam. @MatrixParam extracts information from URL path segments. @HeaderParam extracts information from the HTTP headers. @CookieParam extracts information from the cookies declared in cookie related HTTP headers.

Example (drawn from here):

@Path("/books")
public class BookService {

    @GET
    @Path("{year}")
    public Response getBooks(@PathParam("year") String year,
            @MatrixParam("author") String author,
            @MatrixParam("country") String country) {

        return Response
            .status(200)
            .entity("getBooks is called, year : " + year
                + ", author : " + author + ", country : " + country)
            .build();

    }

}

See following URI patterns and result:

  1. URI Pattern : “/books/2012/”

    getBooks is called, year : 2012, author : null, country : null

  2. URI Pattern : “/books/2012;author=andih”

    getBooks is called, year : 2012, author : andih, country : null

  3. URI Pattern : “/books/2012;author=andih;country=germany”

    getBooks is called, year : 2012, author : andih, country : germany

  4. URI Pattern : “/books/2012;country=germany;author=andih”

    getBooks is called, year : 2012, author : andih, country : germany

For an explanation of the difference you may have a look at URL matrix parameters vs. request parameters

查看更多
够拽才男人
3楼-- · 2020-02-23 07:14

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.

查看更多
登录 后发表回答