使用监听器来优化----分类列表(jdbc底层机制未使用框架)

本文介绍了一种通过监听器在服务器启动时加载分类列表至全局作用域,从而避免重复查询,提升小型项目性能的优化方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用监听器来优化

一个小型项目,页面里面经常要有分类的使用,但是又不经常变动,每次访问都要查询太损耗性能,所以我们把他存储到全局作用域中。只查一次。
在这里插入图片描述
但是什么时候开始查?服务器启动的时候 就开始查询

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();
		}
	}

}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值