我想使用 micronaut 和 groovy 将可选参数传递给 url。我做了很多研究,但找不到任何相关的答案。
@Get('/product/{country}/?
Run Code Online (Sandbox Code Playgroud)
我想将排序和日期作为可选参数传递给此网址。感谢你的帮助。
您可以将可选的排序和日期参数作为查询值传递,如下所示:
@Controller('/')
@CompileStatic
class WithOptionalParameterController {
@Get('/product/{country}{?sort,date}')
String productsForCountry(String country,
@Nullable @Pattern(regexp = 'code|title') String sort,
@Nullable String date) {
"Products for $country sorted by $sort and there is also date $date."
}
}
Run Code Online (Sandbox Code Playgroud)
可以通过指定排序和日期来调用它:
$ curl 'http://localhost:8080/product/chile?sort=code&date=23.3.2020'
Products for chile sorted by code and there is also date 23.3.2020.
Run Code Online (Sandbox Code Playgroud)
或者没有日期:
$ curl 'http://localhost:8080/product/chile?sort=code'
Products for chile sorted by code and there is also date null.
Run Code Online (Sandbox Code Playgroud)
或者没有排序和日期:
$ curl 'http://localhost:8080/product/chile'
Products for chile sorted by null and there is also date null.
Run Code Online (Sandbox Code Playgroud)
POST 示例,您必须@QueryValue为查询参数添加注释:
@Consumes([MediaType.TEXT_PLAIN])
@Post('/product/{country}{?sort,date}')
String productsForCountry(String country,
@Nullable @Pattern(regexp = 'code|title') @QueryValue String sort,
@Nullable @QueryValue String date,
@Body String body) {
"Products for $country sorted by $sort and there is also date $date. Body is $body."
}
Run Code Online (Sandbox Code Playgroud)
可以这样调用:
$ curl -X POST 'http://localhost:8080/product/chile?sort=code&date=23.3.2020' -H "Content-Type: text/plain" -d 'some body'
Products for chile sorted by code and there is also date 23.3.2020. Body is some body.
Run Code Online (Sandbox Code Playgroud)