Spring Bootでクエリパラメータを取得するにはどうすればよいですか?


121

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

7
@RequestParam(良い出発点:公式ガイド
kryger 2015

回答:


196

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

1
次に、このメソッドのURLは何ですか?何を変更する必要がありますか
-Mehandi Hassan 2015

申し訳ありませんが、このURLは機能していませんlocalhost:8888 / user?data = 001このURLを入力しました
Mehandi Hassan '28

3
リクエストマッピングアノテーションからvalue = "/"を削除します。ところで、これは本当に貧弱なデザインです。ユーザーのアイテムにアクセスする場合、残りの方法はuser / items / {itemId}です。
afraisse 2015

17
@RequestParamasとして使用するには、常に存在public @ResponseBody item getitem(@RequestParam("data") String itemid){するデータクエリパラメータが必要です。代わりに、この方法public @ResponseBody item getitem(@RequestParam Map<String, String> queryParameters){で使用すると、データはオプションになります
Sampath Surineni '19 / 01/18

3
...質問の下にコメントを残す代わりに、答えを投稿するべきでした!:-o
kryger 2018年

9

afraisseの承認された回答はの使用に関しては完全に正しい@RequestParamですが、正しいパラメーターが常に使用されているとは限らないため、省略可能<>を使用することをお勧めします。また、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 ....
}

あなたはどこからオプションを手に入れましたか?
ジョーイゴフ

1
@JoeyGoughがJava 8で導入されました。docs.oracle.com/ javase
Andrew

2

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デフォルト
DV82XL

0

私もこれに興味があり、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);
    }

こちらもご覧ください

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.