Spring和JavaWeb整合使用理論的步驟;
1)、Spring來控制事務(dao--JdbcTemplate)
Spring與JavaWeb整合實際的步驟;
1:導包:將aop,ioc,jdbcTemplate,事務管理等的包導入,還有spring的web包;
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.2.6.RELEASE</version> </dependency>
2:寫配置
@Controller:servlet層;目前不能標註在servlet層;
3:因爲Controller層的servlet郵Tomcat管理,所以不能加入容器;如果我們在servlet層手動啓動容器,那麼就沒辦法管理容器中組件的聲明週期;
因此,spring和web整合後,可以在web.xml中註冊監聽器,接管容器
<!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!--這是spring的配置文件位置-->
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
這個監聽器創建好的ioc容器在ContextLoader類中
WebApplicationContext ioc = ContextLoader.getCurrentWebApplicationContext();