如何验证rest路径(spring boot)

6ovsh4lw  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(385)

如何验证从以下url或任何类似的url中给定的路径变量(storeid、customerid、accountid)? /store/{storeId}/customers/{customerId}/accounts/{accountId} 如果用户开始写入 random storeIds/customerIds ,并尝试创建资源,如 POST /store/478489/customers/56423/accounts (假设478489和56423没有指向有效的资源)。我想返回正确的错误代码。 HttpStatus.NOT_FOUND, HttpStatus.BAD_REQUEST .
我在用java和spring boot。
下面的问题更详细地解释了我的问题,但是没有太多的答案。正在验证嵌套资源的路径

ycl3bljg

ycl3bljg1#

从提供的url /store/{storeId}/customers/{customerId}/accounts/{accountId} ,显然 store has customers 还有那些 customers have accounts .
下面的方法包括额外的数据库调用来验证store by id和customer by 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);        
}

上面的代码片段只是您的代码应该是什么样子的一个框架,通过遵循一些好的编码实践,您可以用比上面给出的更好的方式来构造它。
希望对你有帮助。

相关问题