天天看點

Struts2學習知識點總結

1.全局的邏輯控制器為一個過濾器,負責過濾所有的請求。該過濾器引用的API類為

     org.apache.struts2.disapatcher.FilterDispatcher

2.MVC:頁面請求(jsp)——>邏輯控制器(Filter)——>業務控制器(Action)——>業務邏輯元件——>業務處理/DAO

3.struts2的配置檔案放在classpath下。

4.struts2的類型轉換:

       a.繼承DefaultTypeConverter,

          覆寫父類的public Object convertValue(Map context, Object value, Class toType)方法

       b.繼承StrutsTypeConverter,

          覆寫父類的public Object convertFromString(Map context, String[] values, Class toClass)

          該方法負責轉換從頁面傳遞過來的資料。

          覆寫父類的public String convertToString(Map context, Object o)

          該方法負責将Action中處理好的資料轉換成相應格式的字元串。

5.struts2的資料驗證:

       a.使用編碼方式進行驗證。業務控制器Action繼承ActionSupport類,重寫public void validate()方法。

        在該方法中進行資料驗證。若Action中處理業務的方法為test,則可以編寫public void validateTest()

          方法,來對test方法的資料進行驗證。(系統在進行validateTest方法後,會接着執行validate方法,然後

          才執行相應的業務代碼。)

          若嚴重出錯,則可以調用addFieldError或者調用addActionError方法,增加相應的錯誤提示資訊。

       b.使用配置xml檔案進行驗證。驗證檔案的名字為:×××Action-validation.xml。驗證的方式包含字段驗證和非字段驗證。

          其中字段驗證表示對某個字段進行某些類型的驗證。非字段驗證表示用某個類型的驗證來驗證,某個字段。兩種方式

          底層實作一樣,隻是表現方式不同,字段驗證方式比較直覺。

          驗證的類型有一下幾種:required,requiredstring,int,date,double,expression,fieldexpression

         email,url,visitor,conversion,stringLength,regex(正規表達式)。

          對驗證類型可以指定shourt-circuit參數為true,來執行短路驗證。

          如果Action中執行業務的方法為test,則可以通過編寫×××Action-test-validation.xml方法來對test方法的資料進行

          驗證。且執行完test方法的私有驗證檔案後,還會執行預設的驗證檔案×××Action-test-validation.xml的驗證。

       c.struts2進行用戶端的驗證。首先需要使用struts2的标簽庫,且标簽庫的theme屬性不能為simple,然後設定标簽的

         validate屬性為true。

          注意:struts2的用戶端驗證依賴于伺服器的驗證配置檔案。

  6.struts2的攔截器。struts2的攔截器是struts2的核心,其底層實作使用了Java的反射機制與動态代理。在struts2的配置檔案中

      為一個Action引入了一個攔截器,則配置的預設攔截器不會被調用,需要手工配置到該Action中。

      實作struts2攔截器的方法:

        a.實作Interceptor接口,并實作init,destrory以及intercept方法。

        b.繼承AbstractInterceptor類,覆寫intercept方法。

        c.繼承MethodFilterInterceptor類,覆寫intercept方法。該類可以對特定的方法進行攔截。

      攔截器棧可以包含攔截器和攔截器棧。

   7.檔案的上傳和下載下傳:

        a.使用apache組織開發的commons-fileupload和commons-io包,并且按需要配置fileUpload攔截器和相應的上傳參數,

            比如上傳檔案的類型,上傳檔案的大小。多檔案的上傳可以使用js代碼來在頁面修改上傳檔案的清單,在Action中

            則用三個清單分别來儲存檔案對象(file),檔案名(fileName),以及檔案類型(fileContentType)。

        b.檔案下載下傳使用流進行讀取:return ServletActionContext.getServletContext.getResourceAsStream("檔案名")

            并将Action的結果傳回類設定為stream,即流。按需要配置相應的參數。

   8.struts2的國際化。struts2國際化的底層實作用到了Java基礎類庫中的Locale(地區)和ResourceBundle(消息資源)兩個類。

     struts2的國際化主要用在一下幾個地方:

        a.jsp頁面:使用struts2的标簽時,指定标簽的key屬性(對應消息資源檔案中的key)。

                    使用<s:text name="key">

                       <s:param></s:param>

                    </s:text>

                    标簽取得消息資源資訊。

                    還可以用<s:i18n name="basename"></s:i18n>标簽來指定特定的消息資源檔案。

        b.Action中:調用getText(key)或者getText(key,args)方法取得消息資源檔案中的消息資源。

        c.xml驗證檔案中:指定message元素的key屬性(對應消息資源檔案中的key)。(怎麼傳參數?)

        d.類型轉換過程中:通過檢視xwork包的源代碼可以找到:ge.properties檔案中可以找到如下的鍵值對:

                   xwork.default.invalid.fieldvalue=Invalid field value for field "{0}".

                   在消息資源檔案中重新指定該鍵值對即可。

       另外在struts.properties中設定鍵值對struts.i18n.encoding=GBK,可以解決中文亂碼問題。

   9.struts2的異常處理。在Action中,我們的業務邏輯處理方法都對抛出異常進行了聲明。具體的異常對應具體的處理結果。

      在action配置中:

        <action name="upload" class="uploadAction">

          <result name="exception"></result>

          <exception-mapping result="exception" exception="具體的異常類型"></exception-mapping>

      </action>

      還可以配置全局的異常處理:

      <global-exception-mappings>

          <exception-mapping result="" exception=""></exception-mapping>

      </global-exception-mappings>

   struts2的其他東西:

    1.對于struts.xml中的package:

        a.設定<package abstract="true">,則表明該包中沒有action的配置,隻定義一個基礎公共的元件。

        b.package的namespace可以将不同的請求路徑分隔開,在多人合作項目中用到比較多。當接收到一個請求,

            若在目前的namespace中沒有相應的請求位址,則會到預設的namespace中去尋找比對的位址。

    2.模型驅動機制(ModelDriven),将一個Action中的各個參數封裝成為一個JavaBean(類似struts1.x中的

      ActionForm)。需要實作ModelDriven<T>接口,并實作getModel方法。當一個Action實作ModenDriven接口後,

       該Action會被ModenDrivenInterceptor攔截,進行相應的參數設定。

   3.防止表單的重複送出:在jsp的表單中設定<s:token name="***"></s:token>标簽。并且在相應的Action

       中設定token攔截器和名為invalid.token的傳回結果。相應出錯資訊的key為struts.message.invalid.token。

       配置該key,來實作國際化。

    4.struts2中Action與Servlet容器的耦合。主要有三種方式:

         a.實作ServletRequestAware或ServletResponseAware接口。并提供對request或者response熟悉的設定方法。

         b.使用ActionContext(但不能獲得response對象)。改方法友善單元測試。

         c.使用ServletActionContext。ServletActionContext是ActionContext的子類。

       首選使用ActionContext,其次ServletActionContext。

    5.整合多個struts配置檔案,在struts2的配置檔案中使用include元素包含其他的配置檔案。用于多子產品開發。

    6.可以在web.xml中對struts2的核心過濾器FilterDispatcher設定初始化參數(不推薦使用)。

    7.動态方法調用(DynamicMethodInvocation).

         a.action配置中指定:<action name="×××" method="">

         b.在用戶端即頁面指定:<s:form action="method!actionName">

         c.使用通配符:<action name="*Login" class="com.action.LoginAction" method="{1}">,

            若Action的url為helloLogin,則調用LoginAction的hello來處理業務。此種方法簡化了配置,但是

            使得程式不明了,不提倡使用該方法。

    8.struts2的結果類型。在struts2-core包中,有幾種struts2已經配置好的結果類型。

        其中預設的類型為dispatcher,此外還有:redirectAction,chain,freemaker,httpheader,redirect,

        redirectAction,stream,velocity,xslt,plainText。

    9.struts2與spring的整合。導入struts2-spring-plugin包,在web.xml中設定spring的監聽器,

       spring監聽器對應的API類為:org.springframework.web.context.ContextLoaderListener。

       struts2-spring-plugin包為我們将struts2的對象工廠設定為spring的IoC容器,其代碼為:

       <struts>

      <bean type="com.opensymphony.xwork2.ObjectFactory" name="spring" class="org.apache.struts2.spring.StrutsSpringObjectFactory" />

      <!-- Make the Spring object factory the automatic default -->

      <constant name="struts.objectFactory" value="spring" />

      <package name="spring-default">

          <interceptors>

              <interceptor name="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/>

              <interceptor name="sessionAutowiring" class="org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor"/>

          </interceptors>

      </package>   

   </struts>

   很明顯,将struts.objectFactory定位為org.apache.struts2.spring.StrutsSpringObjectFactory

   其餘的工作就交給spring的IoC容器去做了。

   另外:當我們需要增加spring的配置檔案時,需要在web.xml中設定contextConfigLocation參數。代碼如下:

    <context-param>

        <param-name>contextConfigLocation</param-name>

        <param-value>其他的spring配置檔案名,用逗号隔開</param-value>

    </context-param>

   需要注意的一些地方

    1.存儲fieldError的是一個LinkedHashMap<String,ArrayList>;而actionError則存儲在一個ArrayList中。

      ActionSupport中的getFieldError方法傳回的是一個新的集合。該集合是原fieldError集合的一個副本。

       在struts2的源代碼中傳回的是:new LinkedHashMap(internalGetFieldError),即一個新的集合對象。

       是以執行代碼:this.getFieldErrors.put("username","ErrorMsg");不會影響原fieldError集合的資料。

    2.若一個Action注冊了PreResultListner,則會在該Action傳回的時候調用相應結果驗證的邏輯代碼。

    3.struts2-core包中的default.properties和struts-default.xml檔案儲存了一些struts2預設的配置。

       可以在自己的struts配置檔案中對相應的配置進行覆寫或重新設值。比如修改請求的字尾名:在struts.properties

       中加入:

         struts.action.extension = do

       則将struts2請求的字尾名修改成了struts1中的do字尾名的形式。

    4.在配置檔案中配置struts.multipart.saveDir來設定上傳檔案時的臨時檔案的存儲位置。需要定期清理該路徑下的檔案。

繼續閱讀