Java 如何在 Spring Boot 中检索查询参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32201441/
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
How do I retrieve query parameters in Spring Boot?
提问by Mehandi Hassan
I am developing a project using Spring Boot. I've a controller which accepts GETrequests.
我正在使用 Spring Boot 开发一个项目。我有一个接受GET请求的控制器。
Currently I'm accepting requests to the following kind of URLs:
目前我正在接受对以下类型的 URL 的请求:
but I want to accept requests using query parameters:
但我想接受使用查询参数的请求:
Here's the code of my controller:
这是我的控制器的代码:
@RequestMapping(value="/data/{itemid}", method = RequestMethod.GET)
public @ResponseBody
item getitem(@PathVariable("itemid") String itemid) {
item i = itemDao.findOne(itemid);
String itemname = i.getItemname();
String price = i.getPrice();
return i;
}
采纳答案by afraisse
Use @RequestParam
使用@RequestParam
@RequestMapping(value="user", method = RequestMethod.GET)
public @ResponseBody Item getItem(@RequestParam("data") String itemid){
Item i = itemDao.findOne(itemid);
String itemName = i.getItemName();
String price = i.getPrice();
return i;
}
回答by TKPhillyBurb
I was interested in this as well and came across some examples on the Spring Boot site.
我也对此很感兴趣,并在 Spring Boot 站点上看到了一些示例。
// get with query string parameters e.g. /system/resource?id="rtze1cd2"&person="sam smith"
// so below the first query parameter id is the variable and name is the variable
// id is shown below as a RequestParam
@GetMapping("/system/resource")
// this is for swagger docs
@ApiOperation(value = "Get the resource identified by id and person")
ResponseEntity<?> getSomeResourceWithParameters(@RequestParam String id, @RequestParam("person") String name) {
InterestingResource resource = getMyInterestingResourc(id, name);
logger.info("Request to get an id of "+id+" with a name of person: "+name);
return new ResponseEntity<Object>(resource, HttpStatus.OK);
}
回答by Andrew Grothe
While the accepted answer by afraisse is absolutely correct in terms of using @RequestParam
, I would further suggest to use an Optional<> as you cannot always ensure the right parameter is used. Also, if you need an Integer or Long just use that data type to avoid casting types later on in the DAO.
虽然 afraisse 接受的答案在使用方面是绝对正确的@RequestParam
,但我进一步建议使用 Optional<> 因为您不能总是确保使用正确的参数。此外,如果您需要 Integer 或 Long 只需使用该数据类型以避免稍后在 DAO 中转换类型。
@RequestMapping(value="/data", method = RequestMethod.GET)
public @ResponseBody
Item getItem(@RequestParam("itemid") Optional<Integer> itemid) {
if( itemid.isPresent()){
Item i = itemDao.findOne(itemid.get());
return i;
} else ....
}