gpt4 book ai didi

rest - REST Controller Spring 4中的可选@Pathvariable

转载 作者:行者123 更新时间:2023-12-02 08:10:31 27 4
gpt4 key购买 nike

我正在编写一个 Rest 服务(HTTP Get 端点),在下面的 uri 中执行以下操作

http://localhost:8080/customers/{customer_id}
  1. 获取在 uri 中传递的 customer_id 的详细信息
  2. 如果 customer_id 未通过 (http://localhost:8080/customers),则获取所有客户详细信息。

代码:

@RequestMapping(method = RequestMethod.GET, value = "customers/{customer_id}")
public List<Customer> getCustomers(
@PathVariable(name = "customer_id", required = false) final String customerId) {
LOGGER.debug("customer_id {} received for getCustomers request", customerId);

}

但是,使用上面的代码,对于第二种情况,控制流向 getCustomers()。

注意:我使用的是 Java8 和 spring-web 4.3.10 版本

非常感谢您对此提供的任何帮助。

最佳答案

可选的 @PathVariable 仅在您想要将 GET/customers/{customer_id}GET customers 映射到单个 java 方法时使用.

如果您不发送 customer_id,您将无法发送将发送到 GET/customers/{customer_id} 的请求。

所以在你的情况下它将是:

@RequestMapping(method = RequestMethod.GET, value = {"/customers", "customers/{customer_id}"})
public List<Customer> getCustomers(@PathVariable(name = "customer_id", required = false) final String customerId) {
LOGGER.debug("customer_id {} received for getCustomers request", customerId);
}

public abstract boolean required

Whether the path variable is required.

Defaults to true, leading to an exception being thrown if the path variable is missing in the incoming request. Switch this to false if you prefer a null or Java 8 java.util.Optional in this case. e.g. on a ModelAttribute method which serves for different requests.

您可以使用来自 java8 的 nullOptional

关于rest - REST Controller Spring 4中的可选@Pathvariable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47567364/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com