SSM-Web集成

day6

Spring Web 集成

应用上下文对象一启动服务器就创建,创建好的应用上下文对象放到application域中🐟。利用监听器

在Web项目中,可以使用🙆‍ServletContextListener监听Web应用的启动,可以在Web应用启动时加载Spring配置文件

ServletContextListener 是 ServletContext 的监听者,如果 ServletContext 发生变化,如服务器启动时 ServletContext 被创建,服务器关闭时 ServletContext 将要被销毁。在JSP文件中,application 是 ServletContext 的实例,由JSP容器默认创建。Servlet 中调用 getServletContext()方法得到 ServletContext 的实例。

package cn.gyk.listener;
//servletContextListener编写
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* ServletContextListener 监听服务器启动方法
*/
public class ContextLoaderListener implements ServletContextListener {
/**
* 服务器启动的时候初始化方法
* @param servletContextEvent
*/
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
//服务器一启动执行init方法,创建应用上下文对象,这样就可以只加载一次配置问价避免重复加载浪费资源
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
//将Spring应用上下文对象存储到最大的ServletContext域中
ServletContext servletContext = servletContextEvent.getServletContext();
servletContext.setAttribute("app",app);
}
/**
*
* @param servletContextEvent
*/
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}

编写完上面的类之后还需要再web.xml文件中进行配置监听器

<!-- 配置监听器-->
<listener>
<listener-class>cn.gyk.listener.ContextLoaderListener</listener-class>
</listener>

再servlet层获取方式

ServletContext servletContext = req.getServletContext();
ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");
UserService userService = app.getBean(UserService.class);

这样就可以愉快的获取app应用上下文对象了,每次都会使用这一个相比于之前每次用到都会创建新的大大节省了空间资源。

通过全局初始化参数解耦

<!-- 全局初始化参数-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

通过servletcontext.getInitParam()获取定义的全局初始化参数

//读取webxml全局参数
ServletContext servletContext = servletContextEvent.getServletContext();
String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");

Spirng提供获取应用上下文的工具

Spring提供了一个监听器contextLoaderListener,该监听器内部加载Spring配置文件,创建应用上下文,并存储到servletcontext域中,提供了一个客户端工具WebApplicationContextUtils共使用者获得应用上下文对象。

使用步骤

  1. 在web.xml文件中配置监听器,导入 spring-web坐标
  2. 利用WebApplicationContextUtils.getWebApplicationContext()获取servletContext域中的应用上下文对象
posted @   破忒头头  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示