1. 程式人生 > >struts-config.xml中action元素的parameter屬性

struts-config.xml中action元素的parameter屬性

沒有struts之前,使用servlet,最常用的是doGet,doPost,service方法,如果有些經驗的程式設計師會合理的使用這三個方法:如在使用者發出get的請求時,將使用者請求在doGet方法中處理,使用者發出post請求時,將使用者的請求用doPost請求處理,必要時加上service方法去處理那些在一個servlet中必須執行的請求,使用者的請求大體也就這三類,但是如果細分,一個“編輯”,“刪除”,“檢視”等操作都是doGet的範圍,當然也可以都寫到serice方法中或doPost中處理,這樣為了區分這些請求,我們通常都要在程式中加入一個判斷的引數,如:operate,然後在程式中判斷 if operate.equals("update")....,if operate.equals("del")....,if operate.equals("view")....等,實際上這只是個簡單的邏輯,如果業務更加複雜,你可能寫更多的類時operate的引數,這樣就造成程式中有若干if..else if...else if ..,即便你有非常好的編碼規範,整齊的縮排,這個程式也相當難維護;而用到struts時,你又可能把這些引數都寫到execute方法中;那麼最好的方法還是將這些邏輯分開處理,如果執行“編輯”操作的時候呼叫“編輯”對應的方法,執行“刪除”的時候呼叫“刪除”對應的方法...將是比較理想的結果,為了實現這個應用要求,struts引入DispatchAction,這樣你在struts-config.xml檔案的action元素中增加parameter屬性即可實現這個功能:
例如appfuse的配置:
<action
path="/saveUser"
type="org.appfuse.webapp.action.UserAction"
name="userForm"
scope="request"
input="edit"
parameter="method"
unknown="false"
validate="false"
>
<forward
name="list"
path="/WEB-INF/pages/userList.jsp"
redirect="false"
/>
<forward
name="edit"
path="/WEB-INF/pages/userForm.jsp"
redirect="false"
/>
</action>


parameter="method"這個引數就是說,在使用者提交請求時取得method引數,根據method引數呼叫相應的方法,如/editUser.html?method=Delete就是呼叫對應action中的Delete方法,這樣你就可以寫一個Action類處理很多的邏輯,而不是象從前那樣在一個方法裡面加上若干引數,或者直接建若干個action來處理。


例如appfuse的UserAction
package org.appfuse.webapp.action;
import ...


public final class UserAction extends BaseAction { //BaseAction 繼承了DispatchAction


public ActionForward add(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
...
}
public ActionForward cancel(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
...
}
public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
...
}
public ActionForward edit(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
...
}
public ActionForward save(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
...
}
public ActionForward search(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
...
}

public ActionForward unspecified(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {

...
}
private void sendNewUserEmail(HttpServletRequest request, UserForm userForm)
throws Exception {
...
}
}

當你沒有傳入method引數,或者沒有符合引數的方法時,程式將執行unspecified方法;當然method只是一個邏輯名字而已,你也可以使用其他名字,如:method1,method2,go2,asdad等