如何在Spring Boot中检索查询参数?

Meh*_*san 95 java rest spring-boot

我正在使用Spring Boot开发一个项目.我有一个接受GET请求的控制器.

目前我正在接受以下类型网址的请求:

HTTP://本地主机:8888 /用户/数据/ 002

但我想接受使用查询参数的请求:

HTTP://本地主机:8888 /用户数据= 002

这是我的控制器的代码:

@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)

  • 使用**@RequestParam**作为`public @ResponseBody item getitem(@RequestParam("data")String itemid){`要求**data**查询参数始终存在.相反,如果你以这种方式使用它`public @ResponseBody item getitem(@RequestParam Map <String,String> queryParameters){`,它使**数据**成为可选的 (13认同)
  • 从请求映射注释中删除**value ="/"**.顺便说一句,这是非常糟糕的设计.如果您要为用户访问项目,则其余方式为**user/items/{itemId}**. (3认同)
  • 那么你能告诉我这个方法的URL是什么吗?我应该改变什么 (2认同)
  • ...我应该发布答案,而不是在问题下方留下评论!:-o (2认同)

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)

  • 将Optional放入参数中是一个坏主意。不要在参数中使用可选。对于这个问题,可以使用required = false。 (7认同)
  • @JoeyGough 在 Java 8 中引入。 https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html (2认同)
  • @hemanth5636,因为你可以有 3 个可能的值,而不是 2 个......(https://rules.sonarsource.com/java/RSPEC-3553) (2认同)

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)

使用卷曲测试:

  • 卷曲'http://localhost:8080/user/books'
  • 卷曲 'http://localhost:8080/user?book=ofdreams&name=nietzsche'


小智 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。

  • 默认情况下`required = true` (4认同)