When to use @QueryParam vs @PathParam

2019-01-02 19:22发布

I am not asking the question that is already asked here: What is the difference between @PathParam and @QueryParam

This is a "best practices" or convention question.

When would you use @PathParam vs @QueryParam.

What I can think of that the decision might be using the two to differentiate the information pattern. Let me illustrate below my LTPO - less than perfect observation.

PathParam use could be reserved for information category, which would fall nicely into a branch of an information tree. PathParam could be used to drill down to entity class hierarchy.

Whereas, QueryParam could be reserved for specifying attributes to locate the instance of a class.

For example,

  • /Vehicle/Car?registration=123
  • /House/Colonial?region=newengland

/category?instance

@GET
@Path("/employee/{dept}")
Patient getEmployee(@PathParam("dept")Long dept, @QueryParam("id")Long id) ;

vs /category/instance

@GET
@Path("/employee/{dept}/{id}")
Patient getEmployee(@PathParam("dept")Long dept, @PathParam("id")Long id) ;

vs ?category+instance

@GET
@Path("/employee")
Patient getEmployee(@QueryParam("dept")Long dept, @QueryParam("id")Long id) ;

I don't think there is a standard convention of doing it. Is there? However, I would like to hear of how people use PathParam vs QueryParam to differentiate their information like I exemplified above. I would also love to hear the reason behind the practice.

标签: java rest jax-rs
13条回答
梦醉为红颜
2楼-- · 2019-01-02 19:36

You can use query parameters for filtering and path parameters for grouping. The following link has good info on this When to use pathParams or QueryParams

查看更多
君临天下
3楼-- · 2019-01-02 19:38

I think that if the parameter identifies a specific entity you should use a path variable. For example, to get all the posts on my blog I request

GET: myserver.com/myblog/posts

to get the post with id = 123, I would request

GET: myserver.com/myblog/posts/123

but to filter my list of posts, and get all posts since Jan 1, 2013, I would request

GET: myserver.com/myblog/posts?since=2013-01-01

In the first example "posts" identifies a specific entity (the entire collection of blog posts). In the second example, "123" also represents a specific entity (a single blog post). But in the last example, the parameter "since=2013-01-01" is a request to filter the posts collection not a specific entity. Pagination and ordering would be another good example, i.e.

GET: myserver.com/myblog/posts?page=2&order=backward

Hope that helps. :-)

查看更多
冷夜・残月
4楼-- · 2019-01-02 19:41
  1. @QueryParam can be conveniently used with the Default Value annotation so that you can avoid a null pointer exception if no query parameter is passed.

When you want to parse query parameters from a GET request, you can simply define respective parameter to the method that will handle the GET request and annotate them with @QueryParam annotation

  1. @PathParam extracts the URI values and matches to @Path. And hence gets the input parameter. 2.1 @PathParam can be more than one and is set to methods arguments

    @Path("/rest")
    public class Abc {
    
        @GET
        @Path("/msg/{p0}/{p1}")
        @Produces("text/plain")
        public String add(@PathParam("p0") Integer param1, @PathParam("p1")  Integer param2 )
        {
            return String.valueOf(param1+param2);
        }
    } 
    

In the above example,
http://localhost:8080/Restr/rest/msg/{p0}/{p1},
p0 matches param1 and p1 matches param2. So for the URI
http://localhost:8080/Restr/rest/msg/4/6,
we get the result 10.

In REST Service, JAX-RS provides @QueryParam and @FormParam both for accepting data from HTTP request. An HTTP form can be submitted by different methods like GET and POST.

@QueryParam : Accepts GET request and reads data from query string.

@FormParam: Accepts POST request and fetches data from HTML form or any request of the media

查看更多
素衣白纱
5楼-- · 2019-01-02 19:42

I am giving one exapmle to undersand when do we use @Queryparam and @pathparam

For example I am taking one resouce is carResource class

If you want to make the inputs of your resouce method manadatory then use the param type as @pathaparam, if the inputs of your resource method should be optional then keep that param type as @QueryParam param

@Path("/car")
class CarResource
{
    @Get
    @produces("text/plain")
    @Path("/search/{carmodel}")
    public String getCarSearch(@PathParam("carmodel")String model,@QueryParam("carcolor")String color) {
        //logic for getting cars based on carmodel and color
            -----
        return cars
    }
}

For this resouce pass the request

req uri ://address:2020/carWeb/car/search/swift?carcolor=red

If you give req like this the resouce will gives the based car model and color

 req uri://address:2020/carWeb/car/search/swift

If you give req like this the resoce method will display only swift model based car

req://address:2020/carWeb/car/search?carcolor=red

If you give like this we will get ResourceNotFound exception because in the car resouce class I declared carmodel as @pathPram that is you must and should give the carmodel as reQ uri otherwise it will not pass the req to resouce but if you don't pass the color also it will pass the req to resource why because the color is @quetyParam it is optional in req.

查看更多
何处买醉
6楼-- · 2019-01-02 19:42

In nutshell,

@Pathparam works for value passing through both Resources and Query String

  • /user/1
  • /user?id=1

@Queryparam works for value passing only Query String

  • /user?id=1
查看更多
深知你不懂我心
7楼-- · 2019-01-02 19:45

I personally used the approach of "if it makes sense for the user to bookmark a URLwhich includes these parameters then use PathParam".

For instance, if the URL for a user profile includes some profile id parameter, since this can be bookmarked by the user and/or emailed around, I would include that profile id as a path parameter. Also, another considerent to this is that the page denoted by the URL which includes the path param doesn't change -- the user will set up his/her profile, save it, and then unlikely to change that much from there on; this means webcrawlers/search engines/browsers/etc can cache this page nicely based on the path.

If a parameter passed in the URL is likely to change the page layout/content then I'd use that as a queryparam. For instance, if the profile URL supports a parameter which specifies whether to show the user email or not, I would consider that to be a query param. (I know, arguably, you could say that the &noemail=1 or whatever parameter it is can be used as a path param and generates 2 separate pages -- one with the email on it, one without it -- but logically that's not the case: it is still the same page with or without certain attributes shown.

Hope this helps -- I appreciate the explanation might be a bit fuzzy :)

查看更多
登录 后发表回答