Question

How can I get queryparam support of restful web service by spring in true restful manner...

for example i have url like following

localhost:8080/myapp/booksearch/title/{title}/author/{author}?sortby=relevance&year=2013

title and author I can get by @PathVariable .....

where i want sortby and year optional..

Was it helpful?

Solution

You can use the @RequestParam annotation on method parameters

@RequestMapping (...)
public String getBooks(@RequestParam(required = false, value = "sortby") String sortBy, @RequestParam(required = false, value = "year") String year) {...}

The @RequestParam annotation also has a defaultValue attribute to use as a value if the request parameter isn't provided. Without it, if the parameter is not provided, null will be passed as the argument for that parameter.

OTHER TIPS

To get a better order you can use Swagger, it will also let you document your endpoints by the way.

You could use a Class to group your queryParams and pass it as parameter of your Controller's method, like this:

@RequestMapping("/books")
public String getbBoks(MyParams params) {...}

And for describing the params you only have to do this:

@ApiModel
  public class MyParams {
  @ApiParam(
    name = "sortby",
    type = "string",
    required = false
)
private String sortby;

@ApiParam(
    name = "year",
    example = "2017 , 2016",
    type = "integer",
    required = false
)
private int year;
  }

Spring annotation @RequestParam is used to get the query parameter while @PathVariable is used to get the variables in path or url which are declared with curly braces like localhost:8080/myapp/booksearch/title/{title}.

So in your case you need @RequestParam to get the sortedBy and year values. you can simply write public String getBooks(@RequestParam("sortby") String sortBy)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top