java - 如何验证休息路径(弹簧靴)
问题描述
如何验证从以下 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。
以下问题更详细地解释了我的问题,但没有太多回应。 验证嵌套资源的路径
解决方案
从提供的 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);
}
上面的代码片段只是您的代码应该是什么样子的骨架,您可以通过遵循一些良好的编码实践以比上面给出的更好的方式构造它。
我希望它有所帮助。
推荐阅读
- java - 没有可用的“com.jpa.dao.UserRepository”类型的合格 bean
- reactjs - react-native 滚动到底部后如何检查组件是否出现
- python - 是否可以通过/向 Sublime Text 3 添加全局 X11 绑定?
- hadoop - 有没有办法使用 talend 从 hive 中的外部表创建内部表
- lua - Pandoc:在 .md 文件中,如何修改 YAML 元数据块并使用 lua 过滤器将修改后的块放入 markdown 格式
- python - 修复 Python 类中的 TypeError
- arrays - 程序制作一个具有数组搜索和排序的函数
- python - 在 Django 中创建项目管理应用程序 - DAG 和依赖项
- node.js - node.js 全局模块路径在节点脚本中不可访问
- javascript - Javascript - NodeJS 中的 POST 请求不起作用,而它在浏览器中起作用