REST 控制器中可选的@Pathvariable spring 4

Optional @Pathvariable in REST controller spring 4

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

http://localhost:8080/customers/{customer_id}
  1. 获取在 uri
  2. 中传递的 customer_id 的详细信息
  3. 如果 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 版本

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

您应该在此处创建两个端点来处理单个请求:

@GetMapping("/customers")
public List<Customer> getCustomers() {
LOGGER.debug("Fetching all customer");  
}

@GetMapping("/customers/{id}")
public List<Customer> getCustomers(@PathVariable("id") String id) {
LOGGER.debug("Fetching customer by Id {} ",id);  
}

@GetMapping等同于@RequestMapping(method = RequestMethod.GET)@GetMapping("/customers/{id}")等同于@RequestMapping(method = RequestMethod.GET, value = "customers/{id}")

更好的方法是这样的:

@RestController
@RequestMapping("/customers")
public class CustomerController {

    @GetMapping
    public List<Customer> getAllCustomers() {
    LOGGER.debug("Fetching all customer");  
    }

    @GetMapping("/{id}")
    public Customer getCustomerById(@PathVariable("id") String id) {
    LOGGER.debug("Fetching customer by Id {} ",id);  
    }

可选 @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.

您可以使用 nullOptional 来自 java8

这可能对尝试使用多个可选路径变量的人有所帮助。

如果您有多个变量,您总是可以接受多个路径。 例如:

@GetMapping(value = {"customers/{customerId}&{startDate}&{endDate}",
"customers/{customerId}&{startDate}&",
"customers/{customerId}&&{endDate}",
"customers/{customerId}&&"
})
public Customer getCustomerUsingFilter(@PathVariable String customerId, @PathVariable Optional<Date> startDate, @PathVariable Optional<Date> endDate)

然后你会调用这个 URL 使用所有 路径分隔符 (在这种情况下 &)

喜欢
获取/customers/1&& 或
GET /customers/1&&2018-10-31T12:00:00.000+0000 或
GET /customers/1&2018-10-31T12:00:00.000+0000& 或
GET /customers/1&2018-10-31T12:00:00.000+0000&2018-10-31T12:00:00.000+0000