JSF / MyFacesを使用してユーザーロールに基づいて条件を作成する方法
質問
JSPページから現在のユーザーのロールを読み取るには、どのオプションが必要ですか? Tomahawkコンポーネントの visibleOnUserRole =" myRole"
属性を知っていますが、単純な可視性よりも少し複雑な役割が必要です。
解決
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");
}
}
サーブレットでJSFを使用している場合、この情報は HttpServletRequest 。
マネージドBeanを使用して、を介して値をビューに公開できます。式言語。
<f:view>
<h:outputLabel value="#{rolesBean.userPrincipalName}" />
<h:outputLabel value="#{rolesBean.user}" />
<h:outputLabel value="#{rolesBean.manager}" />
</f:view>
他のヒント
Java EE 6(この質問が尋ねられたときは利用できませんでした)では、Faceletsコードの request
変数から直接ロールをテストできます。これは非常に便利です。
E.g。
<h:outputText value="hi, admin!" rendered="#{request.isUserInRole('Admin')}" />
所属していません StackOverflow