《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》,点击传送门,即可获取!
List categorys = categoryService.listCategory();
System.out.println(categorys);
httpServletRequest.getSession().getServletContext().setAttribute(“categorys”,categorys);
return “index”;
}
}
在index.jsp中,我们编写这样一段代码
如果用jquery,代码更简洁~
这样设置,在页面加载之初,就会访问"${pageContext.request.contextPath}/home/index"这个路径,从而也就实现了数据的预加载
三 <jsp:forward page=“后台需要接收的请求”></jsp:forward>
index.jsp作为首页,无法加载需要的页面数据,那么可以让index.jsp不作为展示数据用,用index.jsp直接跳转其他页面;
index.jsp里加<jsp:forward page=“SSM后台接收的请求”></jsp:forward>,携带数据跳转到真正的首页。
四 监听器实现
在传统javaweb中,我们可以使用监听器来实现页面数据预加载
@WebListener
public class ApplicationListener implements ServletContextListener {
public void contextDestroyed(ServletContextEvent sce) {
// 监听器销毁时调用该方法
}
public void contextInitialized(ServletContextEvent sce) {
// 监听器初始化调用该方法
//1.获取application对象
ServletContext application = sce.getServletContext();
//2.查询公告信息存储到application对象中
ReportServiceImpl reportServiceImpl = new ReportServiceImpl();
List list = reportServiceImpl.listReport();
application.setAttribute(“reports”, list);
//3.查询所有的书籍信息存储到application对象中
//4.查询一级分类以及二级分类信息存储到application对象中
}
}
如果我们在ssm中使用监听器,利用IOC的特性,代码变成了这个样子
@WebListener
public class ApplicationListener implements ServletContextListener {
@Autowired
private ReportService reportService;
public void contextDestroyed(ServletContextEvent sce) {
// 监听器销毁时调用该方法
}
public void contextInitialized(ServletContextEvent sce) {
// 监听器初始化调用该方法
//1.获取application对象
ServletContext application = sce.getServletContext();
//2.查询公告信息存储到application对象中
List list = reportService.listReport();
application.setAttribute(“reports”, list);
//3.查询所有的书籍信息存储到application对象中
//4.查询一级分类以及二级分类信息存储到application对象中
}
}
报错了!以上代码在项目启动时会抛出空指针异常!
原因是在ssm中,我们使用依赖注入的方式来操作对象,spring容器会帮助我们管理,监听器的生命周期是由servlet容器(例如tomcat)管理的,项目启动时上例中的ConfigListener是由servlet容器实例化并调用其contextInitialized方法,而servlet容器并不认得@Autowired注解,因此导致ConfigService实例注入失败。
如何解决呢?
这就需要用到spring为我们提供的WebApplicationContextUtils工具类,该工具类的作用是获取到spring容器的引用,进而获取到我们需要的bean实例。
public class PageListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// 监听器初始化调用该方法
//1.获取application对象
System.out.println(“listen调用”);
ServletContext application = sce.getServletContext();
// //2.查询公告信息存储到application对象中
ReportServiceImpl reportService = WebApplicationContextUtils.
getWebApplicationContext(sce.getServletContext()).getBean(ReportServiceImpl.class);
List list = reportService.listReport();
application.setAttribute(“reports”, list);
Docker步步实践
目录文档:
①Docker简介
②基本概念
③安装Docker
④使用镜像:
⑤操作容器:
⑥访问仓库:
⑦数据管理:
⑧使用网络:
⑨高级网络配置:
⑩安全:
⑪底层实现:
⑫其他项目:
《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》,点击传送门,即可获取!
4679114954)]
⑩安全:
[外链图片转存中…(img-wzn1zuKr-1714679114954)]
⑪底层实现:
[外链图片转存中…(img-yNHj4fxu-1714679114954)]
⑫其他项目:
[外链图片转存中…(img-AKqJlpf7-1714679114955)]
《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》,点击传送门,即可获取!