如何使用 JSTL 访问 jsp 中的 "isUserInRole"

How to access "isUserInRole" in jsp using JSTL

我正在使用 MySQL 创建 JSP/Servlet CRUD。我目前在我的项目中有 2 个角色:经理和员工。我想根据这些角色显示不同的数据。如何在不使用 scriptlet 的情况下访问 request.isUserInRole() 方法?我听说使用 scriptlet 不好。

我临时有以下代码:

<c:if <%request.isUserInRole("manager");%>=true> <!-- Display something --> <c:if <%request.isUserInRole("employee");%>=true> <!-- Display something -->

但是我得到一个错误:

HTTP Status 500 - /protected/listUser.jsp (line: 97, column: 9) Unterminated &lt;c:if tag

这可能是 JSTL 与 scriptlet 混合的问题。

如何仅使用 JSTL 访问 JSP 页面中的 isUserInRole() 方法?

您应该使用测试属性指定条件(is required)。

可以通过

实现
  <% request.setAttribute("isManager", request.isUserInRole("manager")); %>
  <c:if test="${requestScope.isManager}">
    <!-- Display manager -->
  </c:if>
  <c:if test="${!requestScope.isManager}">
    <!-- Display employee -->
  </c:if>

或与

  <% request.setAttribute("isManager", request.isUserInRole("manager")); %>
  <c:choose>
    <c:when test="${requestScope.isManager}">
      <!-- Display manager -->
    </c:when>
    <c:otherwise>
      <!-- Display employee -->
    </c:otherwise>
  </c:choose>