根据用户角色渲染JSF组件 [英] Render JSF component based on user role
问题描述
如何根据已登录用户的角色来呈现JSF组件?我知道外部上下文公开了主体,但是我应该如何在JSF中正确进行渲染呢?在JSP中,它将类似于
How do I render JSF components based on a logged in user's role? I know the external context exposes the principals, but how should I do the rendering properly in JSF? In JSP it would be something like
<% isUserInRole(Roles.ADMIN) { %>
<button>Edit!</button>
<% } %>
如何以最佳方式在JSF中编写此代码?我最好的猜测是与返回一个布尔值的backing bean的方法绑定的render属性,但是如果我只为管理员渲染一些导航项,那将引入一个不相关的backing bean.
How do I write this in JSF the best possible way? My best guess is the rendered attribute tied to a backing bean's method that returns a boolean, but that would introduce an irrelevant backing bean if I have to render some navigation items only for admins...
Glassfish V3.1,JSF 2.x
Glassfish V3.1, JSF 2.x
推荐答案
如果您的web.xml
被声明为Servlet 3.0(与JSP/EL 2.2隐式相关)
If your web.xml
is declared as Servlet 3.0 (which implicitly relates to JSP/EL 2.2)
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
then you can take benefit of being able to invoke methods with arguments in EL like as ExternalContext#isUserInRole()
:
rendered="#{facesContext.externalContext.isUserInRole('ADMIN')}"
请注意,这需要支持Servlet 3.0的容器,但是由于您使用的是Glassfish 3(支持Servlet 3.0),因此它应该可以正常工作.
Note that this requires a Servlet 3.0 capable container, but since you're using Glassfish 3 (which supports Servlet 3.0), it should work without any issues.
还要注意,如果您使用Facelets而不是JSP,那么您将具有
Also note that if you're using Facelets instead of JSP, then you've the HttpServletRequest
available as #{request}
in EL, allowing you the following shorter expression:
rendered="#{request.isUserInRole('ADMIN')}"
- 有条件地显示JSF组件
- 非JSF组件(纯原始HTML和模板文本)
- JSF:如何在JSF中控制访问和权限?
- Conditionally displaying JSF components
- Conditional rendering of non-JSF components (plain vanilla HTML and template text)
- JSF: How control access and rights in JSF?
这篇关于根据用户角色渲染JSF组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!