Spring与Web整合

之前java项目中问题:

  1. 手动创建Spring容器

  2. 在其他类需要spring容器, 重复创建

    Spring容器对象的scope: 整个项目只有一个, 创建之后不能销毁, 在其他类共享这个容器对象

整合目的:

  1. 自动创建Spring容器(在服务(Tomcat)启动的时候)

  2. 监听tomcat启动行为, 一旦Tomcat启动触发执行相对应的代码(创建Spring容器), 使用的就是监听器

    javaWeb中, 三剑客: Servlet(接收请求,处理请求), Filter(拦截请求), listener(监听器,监听某个行为, 触发这个行为, 自动执行对应代码,类似前端的事件机制 )

  3. 把Spring容器保存起来, 在其他类重复使用

    Spring容器对象保存到哪? Application域

    保存域中(page域,request域, session域, application域[ServletContext])

整合步骤:

  1. 创建maven的web项目

  2. 在pom.xml文件添加 与web整合的依赖: spring web

    <!--spring-web-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
  3. 在web.xml文件中配置监听器(监听服务器启动), 这个监听器在Spring-web提供了

ApplicationContext接口:

  • ClassPathXmlApplicationContext

  • AnnotationConfigApplicationContext

  • WebApplicationContext:(web环境下的SPring容器)

    <!--配置监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--指定spring的配置文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:beans.xml</param-value>
    </context-param>

把Servlet交给spring管理, service交给Spring管理, 在Servlet注入service, 得到是null

Spring容器中有这个些bean

项目中有几个StudentServlet对象?

有两个:

  1. 使用@Controller注解, 把Servlet对象交给Spring管理, Spring容器有一个

  2. 因为是Servlet类, 请求servlet对象, Tomcat为我们创建Servlet对象, 保存Tomcat的Servlet容器; 有一个 获取Spring容器的方法:

 //ServletContext application = this.getServletContext();

        //ApplicationContext applicationContext = (ApplicationContext)application.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

        //提供一个工具类, 获取Spring容器的工具类
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());

解决方案: 只能在Servlet中,手动getBean获取Service对象

Servlet一定不要交给Spring管理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值