寫 Struts 的 Action 時,常會遇到一種需求:不想每次都固定走 execute,希望能依請求動態決定要呼叫哪個方法。
Struts 本身提供兩條路。第一條是在 struts.xml 的 method 屬性上配置,但一次只能寫死一個方法,無法依請求變化。第二條就是本文要介紹的 DMI(Dynamic Method Invocation),動態方法調用。
package com.bird.test;
import com.opensymphony.xwork2.ActionSupport;
public class IndexAction extends ActionSupport {
private static final long serialVersionUID = 1L;
@Override
public String execute() throws Exception {
return SUCCESS;
}
public String test() {
return ERROR;
}
}
這個 Action 同時有 execute 與 test 兩個方法,我們的目標是動態呼叫 test。
<constant name="struts.devMode" value="true" />
<package name="front" namespace="/front" extends="struts-default">
<action name="index" class="com.bird.test.IndexAction">
<result name="success">/Hello.jsp</result>
<result name="error">/test.jsp</result>
</action>
</package>
配置本身沒有特別之處,關鍵全在請求 URL 的寫法:
https://localhost:8080/Struts2/front/index!test
意思是:呼叫 /front 命名空間下的 index Action,執行其中的 test 方法。最要牢記的就是那個驚嘆號——index!test。
這就是 DMI,一個簡單卻很實用的能力。不過要提醒:直接暴露方法名等於把可呼叫的入口交給外部,正式環境請搭配白名單(struts.enable.DynamicMethodInvocation 與 MethodFilterInterceptor)限制可執行的方法,避免有心人士拿它當跳板。