根据用户角色渲染JSF组件 [英] Render JSF component based on user role

查看:76
本文介绍了根据用户角色渲染JSF组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何根据已登录用户的角色来呈现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">

然后,您可以利用能够调用EL中带有参数的方法的优势,例如

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')}"

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆