JAVA_WEB_自定義ServletContext監聽器

ServletContext監聽器

實現

1.實現ServletContext 監聽器。在容器啓動的時候,用來初始化數據。java

2.實現代碼:web

package com.jeeplus.common.utils;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.modules.sys.entity.DictType;
import com.jeeplus.modules.sys.entity.DictValue;
import com.jeeplus.modules.sys.mapper.DictTypeMapper;
import com.jeeplus.modules.sys.utils.DictUtils;

public class ServletContextInitListener implements ServletContextListener {

	@Autowired
	private DictTypeMapper dictTypeMapper;
	
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("----------------------------servletContenxt init -------------------------------------");
		//每次容器啓動的時候,隨機生成資源版本號
		double version = Math.random();
		ServletContext sc = sce.getServletContext();
		sc.setAttribute("resourceVersion", version);
		// 經過設置這句話,能夠 使用註解來獲取 Spring容器中的bean
		WebApplicationContextUtils.getWebApplicationContext(sc).getAutowireCapableBeanFactory().autowireBean(this);
		//接下來初始化 字典緩存
		Map<String, List<DictValue>> dictMap = (Map<String, List<DictValue>>)CacheUtils.get(DictUtils.CACHE_DICT_MAP);
		if (dictMap==null){
			dictMap = Maps.newHashMap();
			for (DictType dictType : dictTypeMapper.findList(new DictType())){
				List<DictValue> dictList = dictMap.get(dictType.getType());
				dictType = dictTypeMapper.get(dictType.getId());
				if (dictList != null){
					dictList.addAll(dictType.getDictValueList());
				}else{
					dictMap.put(dictType.getType(), Lists.newArrayList(dictType.getDictValueList()));
				}
			}
			CacheUtils.put(DictUtils.CACHE_DICT_MAP, dictMap);
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("----------------------------servletContenxt destory -------------------------------------");
	}

}

複製代碼

注意: 經過設置這句話,能夠 使用註解來獲取 Spring容器中的bean WebApplicationContextUtils.getWebApplicationContext(sc).getAutowireCapableBeanFactory().autowireBean(this);spring

2.web.xml配置監聽。緩存

<listener>
  	<listener-class>com.jeeplus.common.utils.ServletContextInitListener</listener-class>
</listener>
複製代碼
  • 注意:此監聽配置,必定要放到Spring容器的監聽以後,不然獲取不到Bean,報空指針異常。

Q1:SSM + shiro 框架下 ,自定義ServletContext監聽器下,獲取 ServiceBean ,報shiro錯誤 ?

相關文章
相關標籤/搜索