提示:eclipse環境、工程環境、tomcat環境的jdk保持一致
1、新建一個工程,把工程的編碼為utf-8
2、把jsp的編碼形式改成utf-8
3、把jar包放入到lib下 (eclipse下jar包要放在lib下,不能在lib下還有文件夾)
4、建立三個src folder
src 存放源代碼
config 存放配置文件
hibernate 存放hibernate的配置文件
spring 存放spring的配置文件
struts 存放struts的配置文件
struts.xml
test 存放單元測試
5、在src下建立包
cn.itcast.s2sh.domain
持久化類和映射文件
6、編寫dao層和service層
7、寫spring的配置文件
1、寫sessionFactory
2、測試
3、寫dao和service
4、測試
8、寫action
9、寫spring的配置文件
把action注入到spring容器中
<bean id="personAction" class="cn.itcast.s2sh.struts2.action.sh.PersonAction" scope="prototype">
scope為"prototype"保證了action的多實例
10、在web.xml
加入spring的監聽器
加入struts2的過濾器
11、請求
三大框架整合原理
1、三大框架的作用
struts2是一個mvc框架
spring容器
1、利用ioc和di做到了完全的面向接口編程
2、由於spring的聲明式事務處理,使程序員不再關注事務
3、dao層和service層的類是單例的,但是action層是多例
hibernate
就是一個數據庫的ormapping的框架
2、整合原理
1、當tomcat啟動時,做的事情
1、因為在web.xml中,
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext.xml</param-value>
</context-param>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
所以在啟動的時候,執行的是
ContextLoaderListener
contextInitialized
this.contextLoader = createContextLoader();
加載spring的配置文件
這里有一個固定的參數con的textConfigLocation
可以指定classpath路徑下的spring的配置文件
也可以任意位置指定配置文件 spring*.xml WEB-INF/任意多個任意文件夾/spring-*.xml
如果沒有指定固定參數,則查找默認的加載路徑:WEB-INF/applicationContext.xml
this.contextLoader.initWebApplicationContext(event.getServletContext());
啟動spring容器
總結:當tomcat啟動的時候,spring容器就啟動了,這個時候service層和dao層所有的單例類就創建對象了
struts2容器:
加載了default.properties,struts-default.xml,struts-plugin.xml,struts.xml
2、請求一個url時,發生的事情:
1、在引入jar包時,導入了struts2-spring-plugin-2.1.8.1.jar包,該jar中有一個文件struts-plugin.xml
<bean type="com.opensymphony.xwork2.ObjectFactory" name="spring"
class="org.apache.struts2.spring.StrutsSpringObjectFactory" />
<constant name="struts.objectFactory" value="spring" />
2、由於上面的配置改變了action的生成方式,action由StrutsSpringObjectFactory生成,經過查找是由SpringObjectFactory中的buidBean方法
生成的
try {
o = appContext.getBean(beanName);
} catch (NoSuchBeanDefinitionException e) {
Class beanClazz = getClassInstance(beanName);
o = buildBean(beanClazz, extraContext);
}
3、由上面的代碼可以看出,先從spring容器中查找相應的action,如果沒有找到,再根據反射機制創建action,
beanName就是struts配置文件class屬性的值,所以class屬性的值和spring中ID的值保持一致