简体   繁体   English

如何使用JSF / MyFaces基于用户角色创建条件?

[英]How to create conditions based on user role using JSF/MyFaces?

What options do I have to read the roles of the current user from my JSP pages? 我有哪些选项可以从JSP页面中读取当前用户的角色? I'm aware of the visibleOnUserRole="myRole" attribute on Tomahawk components, but I need roles for a bit more complicated things than simple visibility. 我知道Tomahawk组件上的visibleOnUserRole="myRole"属性,但我需要比简单可见性更复杂的角色。

The ExternalContext exposes user and role information. ExternalContext公开用户和角色信息。

public class RolesAccess implements Serializable {

    public String getUserPrincipalName() {
        FacesContext context = FacesContext.getCurrentInstance();
        Principal principal = context.getExternalContext().getUserPrincipal();
        if(principal == null) {
            return null;
        }
        return principal.getName();
    }

    public String getUser() {
        FacesContext context = FacesContext.getCurrentInstance();
        return context.getExternalContext().getRemoteUser();
    }

    public boolean isManager() {
        FacesContext context = FacesContext.getCurrentInstance();
        return context.getExternalContext().isUserInRole("manager");
    }

}

If you're using JSF in servlets, this information maps to the values exposed by the HttpServletRequest . 如果您在servlet中使用JSF,则此信息将映射到HttpServletRequest公开的值。

You can use managed beans to expose values to the view via the Expression Language . 您可以使用托管bean通过表达式语言向视图公开值。

<f:view>
    <h:outputLabel value="#{rolesBean.userPrincipalName}" />
    <h:outputLabel value="#{rolesBean.user}" />
    <h:outputLabel value="#{rolesBean.manager}" />
</f:view>

In Java EE 6 (which wasn't available when this question was asked/answered), you can test roles directly from the request variable in your Facelets code. 在Java EE 6中(在询问/回答此问题时不可用),您可以直接从Facelets代码中的request变量测试角色。 This is super-convenient. 这非常方便。

Eg 例如

<h:outputText value="hi, admin!" rendered="#{request.isUserInRole('Admin')}" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM