简体   繁体   中英

What is the correct way to filter response by query parameter in Spring Boot?

If I have a Get request that returns orders of clients, how can I filter the response to give me the objects that have a specific value for example that are made by those specific clients in Spring Boot? I have tried with @PathVariable and @RequestParams but every attempt failed. Thank you in advance.

If you want to show a specific order which has an identifier of some sort, use @PathVariable . In the following example, the identifier is a String , but in many case it will rather be long or an Integer.

@RestController
@RequestMapping("/orders")
public class OrdersController {

   @GetMapping("/{id}")
   public Order getOrder(@PathVariable("id") String id) {
      // get the order with a specified id from the backend
   }
}

The web request in this case will look like http:/<host>:<port>/orders/123

If you want to filter the order by some name, like 'madeBy John', use Request parameter:

@RestController
@RequestMapping("/orders")
public class OrdersController {

   @GetMapping("/")
   public List<Order> getOrdersFilteredByName(@RequestParam("madeBy") madeBy) {
      // get the order filtered by the person who made the order
      // note, this one returns the list
   }
}

In this case the web request will look like this: http:/<host>:<port>/orders?madeBy=John

Note that technically you can implement whatever you want at the backend, so you can pass, say, John in the first example as a path variable, on server its a String after all, however what I've described is a straightforward and kind-of-standard way of doing these things - so can expect to see this convention in many projects at least.

@RestController
@RequestMapping("/order")
public class OrderController {

    // http://<host>:<port>/order/1    
    @GetMapping("/{id}")
    public Order getOrder(@PathVariable Long id) {
        // Return your order
    }

    // http://<host>:<port>/order?madeBy=John
    @GetMapping("/)
    public List<Order> getOrdersMadeBy(@RequestParam("madeBy") String madeBy) {
        // Return your order list
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM