之前在学习spring时,我们一直在模拟web层,并未使用真正的servlet。下面,我们将开启tomcat服务器,导入servlet/jsp坐标,进入我们所熟悉的、真正的web环境。
web环境带来了我们熟知的servletContext/Session/Request域——想一想,Spring容器(app
)该放到哪个域当中呢?
理解:Spring容器和servletContext域
每次都new
出一个app有着明显的弊端:配置文件被加载多次,容器(上下文对象)被创建多次。
当进入了我们熟悉的web环境,我们有了一个全新的思路解决解决这个问题:
servletContext域是最大的域,每次web项目启动时只加载一次。因此,我们使用ServletContextListener监听web项目,当web项目启动时,就创建一个app并将其存储到servletContext域中。每次需要用到app时,就把它从域中取出来。
也就是说,Spring容器只在web项目启动时,创建了一次。使用new
多次创建的问题得以解决。
实现:手动将app集成到servletContext域中
① 手写ContextLoaderListener监听器
public class ContextLoaderListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
// 1.在web项目启动时创建app上下文对象
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
// 2.将app上下文对象存储到最大的域(ServletContext域)中
ServletContext servletContext = servletContextEvent.getServletContext();
servletContext.setAttribute("app", app);
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
② 在web.xml中配置监听器
<!-- 配置监听器 -->
<listener>
<listener-class>com.samarua.listener.ContextLoaderListener</listener-class>
</listener>
③ 使用(从域中取出app)
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取servletContext域
ServletContext servletContext = req.getServletContext();
// 从域中取出Spring容器
ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");
// 用一下试试 >_<
UserService userService = app.getBean(UserService.class);
userService.sayHi();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
实现:使用Spring提供的监听器和工具类
① 在web.xml中配置
<!-- 全局初始化参数(这是因为在Spring写好的监听器中,xml配置文件的名称不是写死的,而是在这里指定) -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置监听器(这次,我们使用Spring写好的监听器) -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
② 使用(从WebApplicationContextUtils工具类中取出app)
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// // 获取servletContext域
ServletContext servletContext = req.getServletContext();
// 从工具类中取出app
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
// 用一下试试 >_<
UserService userService = app.getBean(UserService.class);
userService.sayHi();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}