zoukankan      html  css  js  c++  java
  • 05Spring集成web

    javaWeb项目有:domain->dao->service->web

    在web层需要编写各种servlet,每个servlet是一个业务,需要调用各种方法、对象,因此需要总是先写:

    ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
    StuService stu = app.getBean(StuService.class);
    

    第一句是加载配置文件,但是不应该每次用的时候调用,而是在服务器启动时加载一次。

    解决该问题的原始方法是:创建ServletContextListener监听器监听web应用的启动,启动时创建ApplicationContext,存储到servletContext域中;关闭时销毁。

    spring框架提供的方法是:使用监听器ContextLoaderListener完成。该监听器内部加载spring配置文件,创建对象,并存储到ServletContext中,并提供了一个客户端工具WebApplicationContextUtils供使用者获取应用上下文对象。

    使用:

    1. 导入spring-web坐标

      <dependency>
      	<groupId>org.springframework</groupId>
      	<artifactId>spring-web</artifactId>
      	<version>5.0.2.RELEASE</version>
      </dependency>
      
    2. 在web.xml中配置ContextLoaderListener监听器(导入spring-web坐标)

      <!--  全局初始化参数-->
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
      </context-param>
      <!--  监听器-->
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      
    3. 在servlet/业务方法中使用WebApplicationContextUtils获取应用上下文对象ApplicationContext

      ServletContext servletContext = this.getServletContext();
      WebApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
      StuService stu = app.getBean(StuService.class);
      stu.save();
      
  • 相关阅读:
    C# 使用SMTP发送附件
    C# 获取文件名及扩展名
    邮件添加附件
    WPF 加载GIF动画
    IIS端口被占用 转载
    ReDim Preserve 的用途
    c# 构造函数执行顺序
    WriteLog
    SMS发送短信设置HttpWebRequest
    Directory.GetFiles
  • 原文地址:https://www.cnblogs.com/mingriyingying/p/13639521.html
Copyright © 2011-2022 走看看