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? I'm aware of the visibleOnUserRole="myRole"
attribute on Tomahawk components, but I need roles for a bit more complicated things than simple visibility.
Asked by: William786 | Posted: 23-01-2022
Answer 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>
Answered by: Byron313 | Posted: 24-02-2022
Answer 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')}" />
Answered by: Kate402 | Posted: 24-02-2022
Similar questions
java - How to create calendar with specified periods in jsf/myfaces? is it possible?
I`m preparing application where user can book a room for specified period. I want to show user a calendar where he will be able to select start and end date of his reservation, but i also want to markup the days in which the room has already been reserved. Is it possible using jsf/myfaces?
Still can't find your answer? Check out these amazing Java communities for help...
Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)