【问题标题】:How do I retrieve query parameters in a Spring Boot controller?如何在 Spring Boot 控制器中检索查询参数?
【发布时间】:2015-11-19 00:09:17
【问题描述】:

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

目前我正在接受对以下类型 URL 的请求:

http://localhost:8888/user/data/002

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

http://localhost:8888/user?data=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;
}

【问题讨论】:

标签: java spring-boot rest spring-mvc


【解决方案1】:

在同一端点接受路径变量和查询参数:

@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;
    }

网址如下:http://localhost:8080/hello/testUser?city=Pune&Pin=411058&state=Maha

【讨论】:

    【解决方案2】:

    在同一个/user 端点中同时接受@PathVariable@RequestParam

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

    使用 curl 进行测试:

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

    【讨论】:

    • 如果你想传递否定句,比如&amp;name!=nietzsche 怎么办?
    【解决方案3】:

    在 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;
    

    @ApiOperation 是来自 Swagger api 的注解,用于记录 api。

    【讨论】:

    • required = true 默认
    【解决方案4】:

    使用 @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;
    }
    

    【讨论】:

    • 请问这个方法的网址是什么?我应该改变什么
    • 对不起兄弟,这个 URL 不起作用 localhost:8888/user?data=001 我已经输入了这个 URL
    • 从请求映射注解中移除 value="/"。顺便说一句,这真是糟糕的设计。如果您要为用户访问项目,那么剩下的方法是 user/items/{itemId}
    • @RequestParam 用作 public @ResponseBody item getitem(@RequestParam("data") String itemid){ 需要始终存在 data 查询参数。相反,如果您以这种方式使用它 public @ResponseBody item getitem(@RequestParam Map&lt;String, String&gt; queryParameters){ ,它会使 data 成为可选
    • ...我应该发布答案而不是在问题下方留下评论! :-o
    【解决方案5】:

    虽然 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 ....
    }
    

    【讨论】:

    【解决方案6】:

    我也对此感兴趣,并在 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);
        }
    

    See here also

    【讨论】:

      猜你喜欢
      • 2020-08-22
      • 1970-01-01
      • 2018-05-03
      • 2010-10-21
      • 1970-01-01
      • 1970-01-01
      • 2021-09-15
      • 2020-02-09
      • 2019-07-14
      相关资源
      最近更新 更多