Search code examples
jspjstlroles

How to access "isUserInRole" in jsp using JSTL


I am making a JSP/Servlet CRUD with MySQL. I currently have 2 roles in my project: manager and employee. I want to display different data based on these roles. How do I access the request.isUserInRole() method without using scriptlets? I heard that using scriptlets are bad.

I temporarily have the following code:

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

But I get an error:

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

Which is probably some problem with JSTL mixing in with a scriptlet.

How would I access the isUserInRole() method in my JSP page with only JSTL?


Solution

  • You should specify condition with test attribute (which is required).

    It could be achieved with

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

    or with

      <% 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>