REST控制器弹簧4中的可选@Path变量

时间:2017-11-30 06:42:39

标签: rest spring-mvc java-8 spring-restcontroller

我正在写一个Rest Service(HTTP Get端点),在下面的uri中有以下内容

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

    @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版本

    非常感谢任何帮助。

3 个答案:

答案 0 :(得分:5)

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

如果您未发送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);
}
  

需要公共抽象布尔值

     

是否需要路径变量。

     

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

您可以使用java8中的nullOptional

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

这可能会帮助那些尝试使用多个视觉路径变量的人。

如果您有多个变量,则始终可以接受多个路径。 例如:

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

然后,您将使用所有路径分隔符(在本例中为&amp;)

调用此URL

如同GET / customers / 1&amp;&amp;或
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

相关问题