Spring-整合web
spring容器是大家用的同一个容器
1导入jar包
spring-web.xml
2.tomcat启动加载配置文件
1 servlet --> init(ServletConfig) --> <load-on-startup>
2 filter --> init(FilterConfig) --> web.xml注册过滤器自动调用初始化
3 listener --> ServletContextListener --> servletContext对象监听【】
spring提供*** ContextLoaderListener --> web.xml <listener><listener-class>....
如果只配置***,默认加载xml位置:/WEB-INF/applicationContext.xml
Spring配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
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_2_5.xsd">
<!-- 确定配置文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置spring ***,加载xml配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.itheima.web.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
</web-app>
从servletContext作用域 获得spring容器 (了解)
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 从application作用域(ServletContext)获得spring容器
//方式1: 手动从作用域获取
ApplicationContext applicationContext =
(ApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
//方式2:通过工具获取
ApplicationContext apppApplicationContext2 =
WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
//操作
AccountService accountService = (AccountService) applicationContext.getBean("accountService");
accountService.transfer("jack", "rose", 1000);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}