1. 程式人生 > >Struts2學習筆記:DMI,多個配置檔案,預設Action,字尾

Struts2學習筆記:DMI,多個配置檔案,預設Action,字尾

動態方法呼叫有三種方法:

1.同一Action多次對映,每個action標籤的method對應要呼叫的方法。

當要呼叫的方法多了就會增加struts.xml檔案的複雜性。

2.struts.DynamicMethodInvocation=true (struts.properties檔案)

或<constant name="struts.enableDynamicMethodInvocation" value=true></constant(struts.xml檔案)

struts.properties檔案優先順序更高

因為常量可以在下面多個配置檔案中進行定義,所以我們需要了解struts2載入常量的搜尋順序: 


struts-default.xml 
struts-plugin.xml 
struts.xml 
struts.properties 
web.xml 

如果在在多個檔案中配置了同一個常量,則後一個檔案中配置的常量值會覆蓋前面檔案中配置的常量值。

這個順序是在多個檔案中配置了同一個常量的前提下,比如struts.action.extension這個常量在struts.xml中有而struts.properties沒有,那麼struts.xml仍會覆蓋預設的值aciton,,

3.萬用字元(官方推薦的方法)

案例:

<action 
name="*_*" class="action.{1}Action" method="{2}"> <result name="success">/{2}_{1}.jsp</result> </action>

訪問http://127.0.0.1:8080/Ch12/User_add.action

呼叫action.UserAction.add(),若業務處理返回success,會跳轉到add_User.jsp

 

指定多個配置檔案:


我們不可能將所有的內容寫在一個struts.xml檔案中,特別是在比較大的應用中更是如此,為便於管理,就可以根據功能的不同寫在不同的.xml檔案中,然後將這些.xml檔案包含在struts.xml檔案中。

1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE struts PUBLIC
3     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
4     "http://struts.apache.org/dtds/struts-2.0.dtd">
5 <struts>
6     <include file="hello.xml"></include>
7     <constant name="struts.i18n.encoding" value="UTF-8"></constant>
8 </struts>

第7行指定了編碼,防止多個xml檔案的編碼格式不同導致亂碼。

hello.xml的內容是實際要配置的action。

 

預設Action:

通常用於顯示404頁面

1 <package name="testStruts" extends="struts-default" namespace="/aaa">
2     <action name="notFound">
3         <result>/404.jsp</result>
4     </action>
5 </package> 

如果action標籤沒有指定class屬性,預設會不經業務邏輯直接跳轉到result。

注意:如果action的name用了萬用字元,首先會去和萬用字元\匹配,如果沒有才會尋找預設的Action

 

Action字尾:

StrutsPrepareAndExecuteFilter是Struts2框架的核心控制器,它負責攔截由<url-pattern>/*</url-pattern>指定的所有使用者請求,當用戶請求到達時,該Filter會過濾使用者的請求。預設情況下,如果使用者請求的路徑不帶字尾或者字尾以.action結尾,這時請求將被轉入Struts 2框架處理,否則Struts 2框架將略過該請求的處理。

* 根據配置檔案:struts2-core-x.x.x.jar包下的org.apache.struts2/default.properties檔案定義的常量決定
    struts.action.extension=action,,

* 預設處理的字尾是可以通過常量”struts.action.extension“進行修改的,如下面配置Struts 2只處理以.do為字尾的請求路徑:

<struts>

    <constant name="struts.action.extension" value="do"/>

</struts>

* 如果使用者需要指定多個請求字尾,則多個字尾之間以英文逗號(,)隔開。如:

    <constant name="struts.action.extension" value="do,go"/>

也可在struts.properties檔案中配置

也可在web.xml中配置

<filter>
      <filter-name>struts2</filter-name>
      <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
      <init-param>
          <param-name>struts.action.extension</param-value>
          <param-value>do,action,,</param-value>
      </init-param>
  </filter>

 

參考:https://www.cnblogs.com/pwc1996/p/4839162.html


另外,result的name屬性區分大小寫,預設是success。如果多個result的name相同(包含多個未指定的情況),那麼將跳轉到最後一個result的頁面