1. 程式人生 > >SSH學習系列篇——整合步驟+原理

SSH學習系列篇——整合步驟+原理

SSH三大框架整合步驟:

     1.新建web工程,並將其編碼設定utf-8

      2.把整個jsp頁面改成utf-8編碼格式

      3.建立三個source folder檔案

             src ----存放原始碼

             config----存放所有的配置檔案,即struts,hibernate和spring配置檔案

              test----存放測試類

      4.在WebRoot\WEB-INF\lib匯入相應的jar包          


整合原理:

1. 配置web.xml檔案

  • spring容器是以監聽器的形式與tomcat整合的
	<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>

說明:

  createContextLoader(),載入springweb容器

initWebApplicationContext:

   * 初始化spring的web容器

  *  載入其配置檔案

總結:

當執行完這兩個方法以後,就啟動spring的web容器了,在spring容器中,單例模式的bean就被例項化了,所以dao和service層的物件和代理物件就在這產生了。

  • 以過濾器的形式整合struts2
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>

tomcat伺服器啟動:一是載入各種配置檔案:default.properties、struts-default.xml、struts-plugin.xml、struts.xml ;二是靜態注入一些bean

2.請求url時 ,步驟如下:

           * 先找struts的配置檔案,根據struts2的相關配置查詢action的建立方式

           *    在uts-default.xml,struts-plugin.xml,struts.xml配置檔案中查詢struts.objectFactory變數由哪個類建立了action,哪個配置檔案載入再最後,哪個決定

* 最後在struts和spring整合的包中找到了struts-plugin.xml檔案

<beantype="com.opensymphony.xwork2.ObjectFactory"

                   name="spring"class="org.apache.struts2.spring.StrutsSpringObjectFactory" />

              <constantname="struts.objectFactory" value="spring" />

 總結:由上述的內容可以知道,action是由StrutsSpringObjectFactory建立,而該類繼承了SpringObjectFactory,並且執行父類的buildBean來建立action

 <pre name="code" class="java"> public Object buildBean (String beanName,Map<String,Object>extraContext,boolean injectInternal) {
               object o = null; 
                try {

                      o = appContext.getBean(beanName);

                    } catch (NoSuchBeanDefinitionException e) {

                       Class beanClazz = getClassInstance(beanName);

                       o = buildBean(beanClazz, extraContext);

                    }

                if  ( injectInternal ){

                    injectInternalBeans(0);

                }
                    return o;
    }
總結:

         由上面的程式碼可以看出,先從spring容器中查詢相應的action,如果沒有找到,再根據反射機制建立action,beanName就是struts2配置檔案中的action元素的class屬性的值,這就意味著class屬性的值要和spring容器中action所在的bean所指定的id值要一致。