Meh*_*san 95 java rest spring-boot
我正在使用Spring Boot开发一个项目.我有一个接受GET请求的控制器.
目前我正在接受以下类型网址的请求:
但我想接受使用查询参数的请求:
这是我的控制器的代码:
@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;
}
Run Code Online (Sandbox Code Playgroud)
afr*_*sse 163
使用@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;
}
Run Code Online (Sandbox Code Playgroud)
And*_*the 19
虽然 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 ....
}
Run Code Online (Sandbox Code Playgroud)
typ*_*gic 19
要在同一端点接受@PathVariable和:@RequestParam/user
@GetMapping(path = {"/user", "/user/{data}"})
public void user(@PathVariable(required=false,name="data") String data,
@RequestParam(required=false) Map<String,String> qparams) {
qparams.forEach((a,b) -> {
System.out.println(String.format("%s -> %s",a,b));
}
if (data != null) {
System.out.println(data);
}
}
Run Code Online (Sandbox Code Playgroud)
使用卷曲测试:
小智 8
要在同一端点中接受路径变量和查询参数:
@RequestMapping(value = "/hello/{name}", method = RequestMethod.POST)
public String sayHi(
@PathVariable("name") String name,
@RequestBody Topic topic,
//@RequestParam(required = false, name = "s") String s,
@RequestParam Map<String, String> req) {
return "Hi "+name +" Topic : "+ topic+" RequestParams : "+req;
}
Run Code Online (Sandbox Code Playgroud)
网址如下: http://localhost:8080/hello/testUser?city=Pune&Pin=411058&state=Maha
小智 5
在Spring boot:2.1.6中,您可以像下面这样使用:
@GetMapping("/orders")
@ApiOperation(value = "retrieve orders", response = OrderResponse.class, responseContainer = "List")
public List<OrderResponse> getOrders(
@RequestParam(value = "creationDateTimeFrom", required = true) String creationDateTimeFrom,
@RequestParam(value = "creationDateTimeTo", required = true) String creationDateTimeTo,
@RequestParam(value = "location_id", required = true) String location_id) {
// TODO...
return response;
Run Code Online (Sandbox Code Playgroud)
@ApiOperation 是来自 Swagger api 的注释,用于记录 api。
| 归档时间: |
|
| 查看次数: |
159827 次 |
| 最近记录: |