REST控制器spring 4中的可选@Pathvariable
问题内容:
我正在编写一个Rest服务(HTTP Get端点),在下面的uri中执行以下操作
http://localhost:8080/customers/{customer_id}
- 获取在uri中传递的customer_id的详细信息
- 如果没有传递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方法时才使用Optional 。
您不能发送的请求将被发送到GET /customers/{customer_id}
如果不发送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);
}
需要公共抽象布尔值
是否需要path变量。
默认为true,如果传入请求中缺少path变量,则会引发异常。如果您希望使用null或Java 8
java.util,请将其切换为false。例如在用于不同请求的ModelAttribute方法上。
您可以使用java8 null
或Optional
从java8