【发布时间】:2022-01-05 15:33:37
【问题描述】:
我有这个代码来检查用户是管理员还是消息的所有者。我必须将此方法拆分为两种方法:第一个 - 检查用户是否为管理员,第二个 - 用户是否为所有者。但是,如果我只是将条件一分为二,它将无法正常工作。
public static void checkIfTheUserIsAdminOrTheOwnerOfTheComment(Comment commentFound, SecurityUser user){
if (!(commentFound.getAuthor().getId().equals(user.getUserId())
||(user.getAuthorities().contains(new SimpleGrantedAuthority(Authorities.ADMIN_WRITE.getPermission()))))) {
throw new ForbiddenRequestException(Errors.ERROR4.getMessage());
}
}
我试过了
public static void checkIfTheUserIsTheOwnerOfTheComment(Comment commentFound, SecurityUser user){
if (!commentFound.getAuthor().getId().equals(user.getUserId())) {
throw new ForbiddenRequestException(Errors.ERROR4.getMessage());
}
}
public static void checkIfTheUserIsAdmin(Comment commentFound, SecurityUser user){
if (!user.getAuthorities().contains(new SimpleGrantedAuthority(Authorities.ADMIN_WRITE.getPermission())))) {
throw new ForbiddenRequestException(Errors.ERROR4.getMessage());
}
}
但它不能正常工作,因为如果我以管理员身份登录,我会遇到我不是所有者的异常,但我必须将它分成两个单独的方法。有什么建议吗?
【问题讨论】:
-
我在 CommentService 类中写了这个表达式,checkIfTheUserIsAdmin(commentFound, user); checkIfTheUserIsTheOwner(commentFound, user);
-
我还是不知道你写了什么或者你是怎么写的。请将该代码添加到您的问题中,而不是对其进行描述。
标签: java spring if-statement exception