首页 > 解决方案 > 如何验证休息路径(弹簧靴)

问题描述

如何验证从以下 URL 或类似内容给出的路径变量(storeId、customerId、accountId)?

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

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

我正在使用带有 Spring Boot 的 Java。

以下问题更详细地解释了我的问题,但没有太多回应。 验证嵌套资源的路径

标签: javaspringspring-bootrestful-authentication

解决方案


从提供的 URL/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);        
}

上面的代码片段只是您的代码应该是什么样子的骨架,您可以通过遵循一些良好的编码实践以比上面给出的更好的方式构造它。

我希望它有所帮助。


推荐阅读