How to conditionally display elements of JSP page depending on user role

房东的猫 提交于 2019-11-29 08:54:10
BalusC

You can just use JSTL to programmatically control the flow in the HTML output of the JSP. You can check the role of the currently logged-in user by HttpServletRequest#isUserInRole() which returns a boolean.

As you're using Servlet 3.0, you'll also be able to take benefit of the new EL 2.2 support of invoking methods with arguments. So, this should do:

<c:if test="${pageContext.request.isUserInRole('admin')}">
    <p>This will be displayed only if the user has the role "admin".</p>
</c:if>
<c:if test="${pageContext.request.isUserInRole('guest')}">
    <p>This will be displayed only if the user has the role "guest".</p>
</c:if>

See also:

You could have different menus in different jsps and then include those jsps based upon the logged in user.

For instance...

<%if(userRole.equals("admin")){%>
   <jsp:include page="../menu/admin_menu.jsp" />
<%}%>
<%if(userRole.equals("user")){%>
   <jsp:include page="../menu/user_menu.jsp" />
<%}%>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!