如何在 JSP/Servlet 中获取用户角色

新手上路,请多包涵

有什么方法可以让 String[] 具有用户在 JSP 或 Servlet 中的角色?

我知道 request.isUserInRole(“role1”) 但我也想知道用户的所有角色。

我搜索了 servlet 源代码,似乎这是不可能的,但这对我来说似乎很奇怪。

那么…有什么想法吗?

原文由 AlfaTeK 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 439
2 个回答

读入所有可能的角色,或硬编码一个列表。然后迭代它运行 isUserInRole 并构建用户所在的角色列表,然后将列表转换为数组。

 String[] allRoles = {"1","2","3"};
HttpServletRequest request = ... (or from method argument)
List userRoles = new ArrayList(allRoles.length);
for(String role : allRoles) {
 if(request.isUserInRole(role)) {
  userRoles.add(role);
 }
}

// I forgot the exact syntax for list.toArray so this is prob wrong here
return userRoles.toArray(String[].class);

原文由 Josh 发布,翻译遵循 CC BY-SA 2.5 许可协议

答案很乱。

首先,您需要找出您的 Web 应用程序中 request.getUserPrincipal() 返回的类型。

     System.out.println("type = " + request.getUserPrincipal().getClass());

假设返回 org.apache.catalina.realm.GenericPrincipal。

然后将 getUserPrincipal() 的结果转换为该类型并使用它提供的方法。

     final Principal userPrincipal = request.getUserPrincipal();
    GenericPrincipal genericPrincipal = (GenericPrincipal) userPrincipal;
    final String[] roles = genericPrincipal.getRoles();

我说这会很乱。它也不是很便携。

原文由 Steve McLeod 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题