1 web.xml

<!-- 配置spring的上下文载入器监听器 ,项目启动时加载spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- 必须放在spring的监听器后面 -->
<listener>
<listener-class>cn.itcast.oa.listener.OAInitListener</listener-class>
</listener>

2

public class OAInitListener implements ServletContextListener {

public void contextDestroyed(ServletContextEvent arg0) {
}

/**
* 初始化方法
*/
public void contextInitialized(ServletContextEvent sce) {
// 1 获取spring容器
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());

// 2从spring容器中获取privilegeService
IPrivilegeService service = (IPrivilegeService) applicationContext.getBean("privilegeServiceImpl");

// 3使用service查询权限数据
List<Privilege> topList = service.findTopList();

// 4将权限数据放入application作用域
sce.getServletContext().setAttribute("privilegeTopList", topList);

System.out.println("权限数据已经放入application作用域了");

//查询所有要进行校验的权限URL
List<String> allUrl = service.findAllUrl();
sce.getServletContext().setAttribute("allUrl", allUrl);
}

3

public List<String> findAllUrl() {
String hql = "SELECT url FROM Privilege WHERE url IS NOT NULL";
return this.getSession().createQuery(hql).list();
}

4 left.jsp

<body style="margin: 0">
<div id="Menu">
<ul id="MenuUl">
<s:iterator value="#application.privilegeTopList">
<!-- 从Session中获取登录用户,根据用户的角色最终获取对应的权限,判断此权限是否和当前循环出的权限是否一致,如果一致就显示 -->
<!-- 使用OGNL调用对象的方法 -->
<s:if test="#session.loginUser.hasPrivilegeByName(name)">
<li class="level1">
<div onclick="menuClick(this);" class="level1Style">
<img src="${pageContext.request.contextPath}/style/images/MenuIcon/${id}.gif" class="Icon"/>${name}
</div>
<ul style="display: none;" class="MenuLevel2">
<s:iterator value="children">
<s:if test="#session.loginUser.hasPrivilegeByName(name)">
<li class="level2">
<div class="level2Style">
<img src="${pageContext.request.contextPath }/style/images/MenuIcon/menu_arrow_single.gif"/>
<a target="right" href="${pageContext.request.contextPath }${url}.do">${name}</a>
</div>
</li>
</s:if>
</s:iterator>
</ul>
</li>
</s:if>
</s:iterator>
</ul>
</div>
</body>

5 ognl

* 判断当前用户是否有给定的权限
*/
public boolean hasPrivilegeByName(String name){//用户删除
//如果登录用户是超级管理员,就直接返回true
if(isAdmin()){
return true;
}

//遍历当前用户对象的角色
for(Role role : roles){
Set<Privilege> privileges = role.getPrivileges();
//遍历角色对应的权限集合
for(Privilege p : privileges){
String pName = p.getName();
if(pName.equals(name)){
return true;
}
}
}
return false;
}