繁体   English   中英

如何验证 rest 路径(弹簧启动)

[英]How to validate rest path (spring boot)

如何验证从以下 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 引导。

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

从提供的 URL /store/{storeId}/customers/{customerId}/accounts/{accountId}可以看出, store has customers ,这些customers have accounts

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

如果您一步一步 go 可以显示相应的错误消息,

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

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

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

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

我希望它有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM