[英]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?如果我有一个返回客户端订单的 Get 请求,我如何过滤响应以向我提供具有特定值的对象,例如由 Spring Boot 中的特定客户端生成的对象? I have tried with @PathVariable and @RequestParams but every attempt failed.我尝试过使用@PathVariable 和@RequestParams,但每次尝试都失败了。 Thank you in advance.先感谢您。
If you want to show a specific order which has an identifier of some sort, use @PathVariable
.如果要显示具有某种标识符的特定订单,请使用@PathVariable
。 In the following example, the identifier is a String
, but in many case it will rather be long or an Integer.在下面的示例中,标识符是一个String
,但在许多情况下它会很长或 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
在这种情况下,web 请求看起来像http:/<host>:<port>/orders/123
If you want to filter the order by some name, like 'madeBy John', use Request parameter:如果您想按某个名称过滤订单,例如“madeBy John”,请使用请求参数:
@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
在这种情况下,web 请求将如下所示: 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.请注意,从技术上讲,您可以在后端实现您想要的任何内容,因此您可以将第一个示例中的John
作为路径变量传递,在服务器上它毕竟是一个字符串,但是我所描述的是一个简单而亲切的 -做这些事情的标准方式 - 所以至少可以在许多项目中看到这种约定。
@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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.