在Spring Boot中,通过查询参数过滤响应的正确方法是什么



如果我有一个返回客户端订单的Get请求,我如何过滤响应以向我提供具有特定值的对象,例如由Spring Boot中的特定客户端创建的对象?我尝试过@PathVariable和@RequestParams,但每次尝试都失败了。提前谢谢。

如果要显示具有某种标识符的特定订单,请使用@PathVariable。在下面的示例中,标识符是String,但在许多情况下,它更倾向于长或整数。

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

这种情况下的web请求看起来像http:/<host>:<port>/orders/123

如果你想用一些名字过滤订单,比如"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
}
}

在这种情况下,web请求将如下所示:http:/<host>:<port>/orders?madeBy=John

请注意,从技术上讲,您可以在后端实现任何您想要的东西,所以您可以在第一个示例中将John作为路径变量传递,毕竟在服务器上它是一个String,但是我所描述的是一种简单而标准的方式来做这些事情,所以至少可以在许多项目中看到这种约定。

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

最新更新