SpringMvc自定义监听器以及从Controller获取Application域对象

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();
        //通过applicationContext获取Spring的bean对象
        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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值