ECApp -- 之系統(tǒng)初始化
在java web項(xiàng)目中,最常用的就是使用listener來(lái)實(shí)現(xiàn)初始化了。
下面是實(shí)現(xiàn)代碼
這樣我們就可以在系統(tǒng)啟動(dòng)的時(shí)候?qū)⒁恍┏S玫臄?shù)據(jù)及配置信息都放到內(nèi)存(即serlvetContext里面),在struts2中,我們可以通過(guò)這種方式獲得
ServletContext context = ServletActionContext.getServletContext();
然后就可以使用存放在context里面的數(shù)據(jù)了。
就這么簡(jiǎn)單。
下面是實(shí)現(xiàn)代碼
1 public class StartupListener extends ContextLoaderListener implements
2 ServletContextListener {
3
4 private Logger logger = LoggerFactory.getLogger(getClass());
5
6 /**
7 * web容器啟動(dòng)時(shí)調(diào)用
8 */
9 public void contextInitialized(ServletContextEvent event) {
10 logger.info("application servlet initialized

");
11
12 ServletContext context = event.getServletContext();
13
14 //從spring中獲得bean,由這個(gè)bean進(jìn)行相應(yīng)操作,結(jié)果存到context中
15 ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
16 ProductClassManager productClassManager = (ProductClassManager)ctx.getBean("productClassManager");
17
18 String prodClassTreeJson = productClassManager.generateProdClassTree();
19
20 context.setAttribute(Constants.PRODUCT_CLASS_JSON_STRING, prodClassTreeJson);
21 }
22
23
24 /**
25 * web容器銷毀時(shí)調(diào)用
26 */
27 public void contextDestroyed(ServletContextEvent event){
28 logger.info("application servlet destroyed

");
29 }
30
31 }
這里面還調(diào)用 了spring的bean,所以listener要配置在spring的那個(gè)listener下面,否則可能出錯(cuò)。2 ServletContextListener {
3
4 private Logger logger = LoggerFactory.getLogger(getClass());
5
6 /**
7 * web容器啟動(dòng)時(shí)調(diào)用
8 */
9 public void contextInitialized(ServletContextEvent event) {
10 logger.info("application servlet initialized



11
12 ServletContext context = event.getServletContext();
13
14 //從spring中獲得bean,由這個(gè)bean進(jìn)行相應(yīng)操作,結(jié)果存到context中
15 ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
16 ProductClassManager productClassManager = (ProductClassManager)ctx.getBean("productClassManager");
17
18 String prodClassTreeJson = productClassManager.generateProdClassTree();
19
20 context.setAttribute(Constants.PRODUCT_CLASS_JSON_STRING, prodClassTreeJson);
21 }
22
23
24 /**
25 * web容器銷毀時(shí)調(diào)用
26 */
27 public void contextDestroyed(ServletContextEvent event){
28 logger.info("application servlet destroyed



29 }
30
31 }
這樣我們就可以在系統(tǒng)啟動(dòng)的時(shí)候?qū)⒁恍┏S玫臄?shù)據(jù)及配置信息都放到內(nèi)存(即serlvetContext里面),在struts2中,我們可以通過(guò)這種方式獲得
ServletContext context = ServletActionContext.getServletContext();
然后就可以使用存放在context里面的數(shù)據(jù)了。
就這么簡(jiǎn)單。
posted on 2009-08-06 15:40 風(fēng)人園 閱讀(254) 評(píng)論(0) 編輯 收藏 所屬分類: ECP