How to show different menu according to rule of us

2019-04-02 02:11发布

问题:

I am using tile3, spring security and struts2. I have different number of users, each with specific role, and each role should has access to a specific menu, I have the follwoing tile.xml file but I am not sure how to change it in a way to solve the issue.

Please let me know if you need me to provide any other part of my code.

<tiles-definitions>
    <definition name="baseLayout" template="/baseLayout.jsp">
        <put-attribute name="title"  value=""/>
        <put-attribute name="header" value="/header.jsp"/>
        <put-attribute name="menu" value=""/>
        <put-attribute name="body"   value=""/>
        <put-attribute name="footer"   value="/footer.jsp"/>
        <put-attribute name="register"  value="/register.jsp"/>
    </definition>

    <definition name="register1" extends="baseLayout">
        <put-attribute name="menu"   value="/menuAdmin.jsp"/>  
        <put-attribute name="body" value="/body.jsp"/>
    </definition>
    <definition name="register2" extends="baseLayout">
        <put-attribute name="menu"   value="/menuUser.jsp"/>  
        <put-attribute name="body" value="/body.jsp"/>    
     </definition>
       .....

As my application has many different pages, I have to create a separate definition for each request for each user's role. For example, there should only be a definition called register and the menu attribute should dynamically change based on role of requester, or any other way to make it simpler.

I am using the following to define the accessible sections for each role

<http auto-config="true" access-denied-page="/notFound.jsp" use-expressions="true">
    <intercept-url pattern="/Profile/view*" access="hasRole('ROLE_ADMIN')" /> 
    <intercept-url pattern="/Search/view*" access="hasRole('ROLE_ADMIN')" /> 
    <form-login login-page="/index" 
                authentication-failure-url="/index?error=1"
                default-target-url="/default"/> 
     <logout logout-success-url="/index.jsp"/>
</http> 

I can use the following code to find the logged in user's role

 @Action
 public class Default {
    public String execute(){
        String role =    
        SecurityContextHolder.getContext().getAuthentication().getAuthorities().toString();
        System.out.println("User's role:"+role);
        if(role.equalsIgnoreCase("[ROLE_ADMIN]"))
            return "Admin";
        return "";


    }

}

回答1:

Use the following

 <put-attribute name="header" expression="OGNL:@com.project.Default@getRole() + '.jsp'"/>