以一例分析:
页面操作:
<a href="servlet/LoginServlet">LOGIN</a>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!--
web容器中注册一个负责加载spring框架的中央控制器
ContextLoaderListener
阶段1 : tomcat启动时,首先加载工程中的web.xml文件;
初始化web容器中注册的ContextLoaderListener监听器;
执行监听器的初始化方法,在方法中负责查找当前web容器中是否存在一个spring环境[ioc容器/applicationContext.xml]
监听器会在web容器中查找一个名为contextConfigLocation的初始化参数
将该参数的值作为spring的ioc容器进行加载
阶段2 : 找到spring的ioc容器之后,需要对ioc容器进行解析
[BeanFactory实现类才具备解析ioc容器的能力]
监听器没有能力解析ioc容器
监听器会创建一个负责解析ioc容器的WebApplicationContext
由于创建的是ApplicationContext类型的ioc工厂负责解析ioc容器
会在解析ioc容器时实例化容器内配置的所有bean
[ioc容器中配置的bean 是在tomcat启动时 初始化]
阶段3 : ioc容器解析完毕之后,监听器会将其创建的WebApplicationContext
存储在ServletContext范围中供以后使用
-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.etoak.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/servlet/LoginServlet</url-pattern>
</servlet-mapping>
<!-- 全局的初始化参数 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!--
根目录 fileSystem
src目录 classpath
<param-value>classpath:applicationContext.xml</param-value>
WEB-INF目录 web容器
-->
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<bean id="dao" class="com.etoak.dao.UserDaoImpl"
init-method="init"></bean>
</beans>
LoginServlet.java
public class LoginServlet extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 处理客户端提交的servlet/LoginServlet请求
/** 主动调用ioc工厂 获取工厂管理的bean
* factory.getBean("dao")
* 谁解析的ioc容器/谁实例化的bean,就必须使用谁的getBean()获取ioc容器中的bean
* WebApplicationContext.getBean("xx")
* ServletContext
*/
// 1 获取ServletContext
ServletContext sc = request.getSession().getServletContext();
// 2 从ServletContext中获取WebApplicationContext
WebApplicationContext ac =
WebApplicationContextUtils
.getWebApplicationContext(sc);
// 3 通过工厂获取ioc容器中的bean
UserDaoImpl ud = (UserDaoImpl)ac.getBean("dao");
ud.login();
}
}
UserDaoImpl.java
public class UserDaoImpl {
public void init(){
System.out.println("UserDaoImpl被初始化了");
}
public boolean login(){
System.out.println("连接数据库判断登录是否成功");
return true;
}
}