Springzz中使用监听器,用于容器一启动就加载准备数据(application范围内的数据,用于减轻服务器压力,不用每次都去查数据)

java代码:

public class InitListener implements ServletContextListener {

public void contextInitialized(ServletContextEvent sce) {
// 获取容器与相关的Service对象
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
PrivilegeService privilegeService = (PrivilegeService) ac.getBean("privilegeServiceImpl");

// 准备数据:topPrivilegeList
List<Privilege> topPrivilegeList = privilegeService.findTopList();
sce.getServletContext().setAttribute("topPrivilegeList", topPrivilegeList);
System.out.println("------------> 已准备数据topPrivilegeList <------------");

// 准备数据:allPrivilegeUrls
Collection<String> allPrivilegeUrls = privilegeService.getAllPrivilegeUrls();
sce.getServletContext().setAttribute("allPrivilegeUrls", allPrivilegeUrls);
System.out.println("------------> 已准备数据allPrivilegeUrls <------------");
}

public void contextDestroyed(ServletContextEvent arg0) {

}
}

 

web.xml中的配置如下:

<!-- 配置Spring的用于初始化容器对象的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>

<!--
用于做初始化工作的监听器,一定要配置到Spring的ContextLoaderListener之后,因为要用到Spring的容器对象
-->
<listener>
<listener-class>cn.util.InitListener</listener-class>
</listener>

 

在jsp中获取数据:

<s:iterator value="#application.topPrivilegeList">

 

posted @ 2016-09-10 23:18  江山一族  阅读(473)  评论(0编辑  收藏  举报