使用监听器来优化
一个小型项目,页面里面经常要有分类的使用,但是又不经常变动,每次访问都要查询太损耗性能,所以我们把他存储到全局作用域中。只查一次。
但是什么时候开始查?服务器启动的时候 就开始查询
servletContextListener
在创建的时候 也可以右键搜索listener next 选择你要实现的接口
/**
* 当服务器启动时,将分类列表查询出来并且存储到application作用域中
*/
public class ApplicationListener implements ServletContextListener {
private NewsCategoryService newsCategoryService = new NewsCategoryServiceImpl();
public ApplicationListener() {
}
public void contextDestroyed(ServletContextEvent sce) {
}
/**
* 有异常就处理一下 因为是重写的方法 不能抛
* 在这里写了以后 以后凡是在其他页面需要用到他的 直接获取就可以
* 因为是存到了全局作用域中 你在获取的时候可以借助el表达式 它会默认从(page -> request -> session -> application依次查找数据(范围小 -> 范围大)
* @see ServletContextListener#contextInitialized(ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent event) {
try {
List<NewsCategory> categoryList = newsCategoryService.getList();
ServletContext application = event.getServletContext();
application.setAttribute("categoryList", categoryList);
} catch (Exception e) {
e.printStackTrace();
}
}
}