Optional @Pathvariable in REST controller spring 4

我怕爱的太早我们不能终老 提交于 2019-12-06 07:26:55

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

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

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.

You can use null or Optional from java8

This may help someone that is trying to use multiple opcional path variables.

If you have more than one variable you can always accept multiple paths. For instance:

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

Then you would call this url using all the path separators ( in this case & )

Like
GET /customers/1&& or
GET /customers/1&&2018-10-31T12:00:00.000+0000 or
GET /customers/1&2018-10-31T12:00:00.000+0000& or
GET /customers/1&2018-10-31T12:00:00.000+0000&2018-10-31T12:00:00.000+0000

You should create two end-point here to handle the individual request :

@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 is equivalent to @RequestMapping(method = RequestMethod.GET) and @GetMapping("/customers/{id}") is equivalent to @RequestMapping(method = RequestMethod.GET, value = "customers/{id}")

Better approach would be like this :

@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);  
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!