如何验证休息路径(春季启动)

如何验证通过以下URL或类似内容提供的路径变量(storeId,customerId,accountId)?

/store/{storeId}/customers/{customerId}/accounts/{accountId}

如果用户开始写random storeIds/customerIds,并尝试创建类似 URL中的POST /store/478489/customers/56423/accounts(假设478489和56423没有指向有效的资源)。 我想返回正确的错误代码,例如HttpStatus.NOT_FOUND,HttpStatus.BAD_REQUEST

我将Java与Spring Boot配合使用。

以下问题更详细地说明了我的问题,但是并没有太多答复。 Validating path to nested resource

a714618777 回答:如何验证休息路径(春季启动)

从提供的网址/store/{storeId}/customers/{customerId}/accounts/{accountId}中, 显然store has customers和那些customers have accounts

以下方法包括额外的数据库调用,用于按ID验证商店和按ID验证顾客,但这将是适当的方法,因为如果我们在STORE和CUSTOMER表上使用带有联接的查询,那么您可能无法准确判断给定的storeId或customerId不正确/不在数据库中。

如果您逐步进行操作,则可以显示相应的错误消息,

如果storeId不正确-There exists no store with given storeId: XYZ 如果customerId不正确-There exists no customer with customerID: XYZ

由于您提到您正在使用Spring Boot,因此您的代码应如下所示:

@RequestMapping(value = "/store/{storeId}/customers/{customerId}/accounts",method = RequestMethod.POST)
public ResponseEntity<Account> persistAccount(@RequestBody Account account,@PathVariable("storeId") Integer storeId,@PathVariable("customerId") Integer customerId) {

    // Assuming you have some service class @Autowired that will query store by ID.
    // Assuming you have classes like Store,Customer,Account defined
    Store store = service.getStoreById(storeId);
    if(store==null){
        //Throw your exception / Use some Exception handling mechanism like @ExceptionHandler etc.
        //Along with proper Http Status code.
        //Message will be something like: *There exists no store with given storeId: XYZ*
    }
    Customer customer = service.getAccountById(storeId,customerId);
    if(customer==null){
        //Throw your exception with proper message.
        //Message will be something like: *There exists no store with given customerID: XYZ*
    }
    // Assuming you already have some code to save account info in database.
    // for convenience I am naming it as saveAccountAgainstStoreAndCustomer
    Account account = service.saveAccountAgainstStoreAndCustomer(storeId,customerId,account);
    ResponseEntity<Account> responseEntity = new ResponseEntity<Account>(account,HttpStatus.CREATED);        
}

以上代码段只是代码外观的骨架,通过遵循一些良好的编码惯例,您可以以比上面给出的更好的方式来对其进行结构化。

希望对您有帮助。

本文链接:https://www.f2er.com/3092259.html

大家都在问