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

懵懂的女人 提交于 2019-12-13 15:12:44

问题


What options do I have to read the roles of the current user from my JSP pages? I'm aware of the visibleOnUserRole="myRole" attribute on Tomahawk components, but I need roles for a bit more complicated things than simple visibility.


回答1:


The ExternalContext exposes user and role information.

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.

You can use managed beans to expose values to the view via the Expression Language.

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



回答2:


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. This is super-convenient.

E.g.

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


来源:https://stackoverflow.com/questions/286686/how-to-create-conditions-based-on-user-role-using-jsf-myfaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!