我的配置中有一个拦截器,我想禁止访问其他用户的资源。在 WebMvcConfig(实现 WebMvcConfigurer)中,我有:@Overridepublic void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new FolderInterceptor(userService, folderService)) .addPathPatterns(Mapping.FOLDER_MAPPING + "/{id}", Mapping.UPDATE_FOLDER_MAPPING + "/{id}", Mapping.DELETE_FOLDER_MAPPING + "/{id}", Mapping.DOWNLOAD_FOLDER_MAPPING + "/{id}");}在我的 FolderInterceptor 中,我有一个 preHandle 方法获取访问的文件夹并检查其所有者:Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);Long id = Long.valueOf((String) pathVariables.get("id"));User user = userService.getLoggedAccount();if (folderService.existsById(id)) { Folder folder = folderService.findById(id); if (folder.getOwner().getId().equals(user.getId())) { return true; } else { response.sendError(403, "Unauthorized"); return false; }}else { response.sendError(404, "Folder does not exist"); return false;}如果我打印文件夹对象,我在该行有同样的错误。org.hibernate.LazyInitializationException: could not initialize proxy.谢谢您的帮助。
2 回答
UYOU
TA贡献1878条经验 获得超4个赞
我使用 getOne 方法在我的服务中按 id 检索我的文件夹。现在使用 folderRepository.findById(id) 并且现在可以使用:
public Folder findById(Long id) {
Optional<Folder> folder = folderRepository.findById(id);
if (!folder.isPresent())
return null;
return folder.get();
}
繁花不似锦
TA贡献1851条经验 获得超4个赞
您很Folder可能正在检索一个实体,而无需在此处的一个事务下获取任何依赖项:
Folder folder = folderService.findById(id);
然后,当您尝试访问时folder.getOwner(),没有获取 Owner 依赖项,并且持久性提供程序尝试从数据库中延迟加载它:
if (folder.getOwner().getId().equals(user.getId())) {
return true;
}问题在于它folder超出了事务范围和一个分离的实体。
我建议获取方法Owner 内部folderService.findById(id)或将查询和条件置于相同的事务方法下。
添加回答
举报
0/150
提交
取消
