動態方法調用有三種方法:
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.通配符(官方推薦的方法)
案例:
<!--索引下標從1開始-->
<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的頁面