Java 在 spring 中支持 queryparm 以实现 RESTful Web 服务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18936861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
queryparm support in spring for restful web services
提问by Ram Sharan Mittal
How can I get queryparam
support of restful web service by spring in true restful manner...
我怎样才能queryparam
在春天以真正宁静的方式获得宁静的 Web 服务的支持......
for example i have url like following
例如我有如下网址
localhost:8080/myapp/booksearch/title/{title}/author/{author}?sortby=relevance&year=2013
本地主机:8080/myapp/booksearch/title/{title}/author/{author}?sortby=relevance&year=2013
title and author I can get by @PathVariable
.....
标题和作者我可以通过@PathVariable
.....
where i want sortby and year optional..
我想要排序和年份可选的地方..
采纳答案by Sotirios Delimanolis
You can use the @RequestParam
annotation on method parameters
您可以@RequestParam
在方法参数上使用注释
@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.
该@RequestParam
注释还具有defaultValue
如果不设置请求参数被作为值使用属性。没有它,如果未提供参数,null
将作为该参数的参数传递。
回答by dmarquina
To get a better order you can use Swagger, it will also let you document your endpoints by the way.
为了获得更好的订单,您可以使用 Swagger,顺便说一下,它还可以让您记录端点。
You could use a Class to group your queryParams and pass it as parameter of your Controller's method, like this:
您可以使用 Class 对您的 queryParams 进行分组并将其作为控制器方法的参数传递,如下所示:
@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;
}