SpringMvc自定义监听器
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
@Component
public class sysInitListener implements ServletContextListener, ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext servletContext = sce.getServletContext();
DicService dicService = applicationContext.getBean(DicService.class);
Map<String, List<DicValue>> map = dicService.getAll();
Set<String> keys = map.keySet();
for (String key : keys) {
servletContext.setAttribute(key,map.get(key));
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
sysInitListener.applicationContext =applicationContext;
}
}
实现一个用于自定义监听器 实现要实现**ServletContextListener**接口
由于我们要获取spring容器 所以我们还要实现**ApplicationContextAware**接口 并且实现对 应的方法。
需要注意的是我们的监听器配置代码的位置一定要在spring监听器的下面 因为我们的监 听器依赖于spring监听器
<listener>
<listener-class>cn.it.crm.web.listener.sysInitListener</listener-class>
</listener>
application:全局作用范围,整个应用程序共享,
就是在部署文件中的同一个webApp共享
生命周期为:应用程序启动到停止
HttpServletRequest
request.getSession().getServeltContext(). 返回值就是application 当前对象 的appliaction的值
给处理器方法添加参数: request.getSession().getServletContext().setAttribute("key","value"); 即可将数据存入application。
从Controller获取Application域对象
@RequestMapping("/getDic")
public @ResponseBody
Map<String, Object> getDic(HttpServletRequest request) {
HashMap<String, Object> map = new HashMap<>();
ServletContext servletContext = request.getSession().getServletContext();
Enumeration<String> attributeNames = servletContext.getAttributeNames();
Object obj = null;
while (attributeNames.hasMoreElements()) {
String s = attributeNames.nextElement();
if (!s.contains(".")) {
obj = servletContext.getAttribute(s);
map.put(s, obj);
}
}
return map;
}