REST控制器弹簧4中的可选@Pathvariable

问题描述:

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

I'm writing a Rest Service (HTTP Get endpoint), where in the below uri does the following

http://localhost:8080/customers/{customer_id}




  1. 获取详细信息对于在uri中传递的customer_id

  2. 如果未传递customer_id( http:/ / localhost:8080 / customers ),获取所有客户详细信息。

  1. fetch the details for the customer_id passed in the uri
  2. if the customer_id is not passed (http://localhost:8080/customers), fetch all the customers details.

代码:

@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()。

However, with the above code, for the second scenario control is flowing to getCustomers().

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

Note: I'm using Java8 and spring-web 4.3.10 version

非常感谢任何帮助。

可选 @PathVariable 仅当您要将 GET / customers / {customer_id} GET客户映射到单个java方法时才使用。

Optional @PathVariable is used only if you want to map both GET /customers/{customer_id} and GET customers into single java method.

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

You cannot send request which will be sent to GET /customers/{customer_id} if you don't send customer_id.

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

So in your case it will be:

@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

是否需要路径变量。

默认为true,如果路径变量丢失,则会导致抛出异常来电请求。如果您在这种情况下更喜欢null或Java 8 java.util.Optional,请将其切换为false。例如在一个ModelAttribute方法,用于不同的请求。

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.

你可以使用 null 或来自java8的可选

You can use null or Optional from java8