使用DispatchAction类,为系统减肥

来源:互联网 发布:java基础知识考试题目 编辑:程序博客网 时间:2024/05/01 04:06

使用DispatchAction类,为系统减肥!

Struts中你要尽可能的不用Action类,因为他们让你的项目变得臃肿,你可以使用org.apache.struts.actions.DispatchAction类来完成业务逻辑所需要的相关操作集中到一个Action类中,在继承DispatchAction后,你不再是重新定义execute()方法,而是编写你自己的业务方法,execute()方法在DispatchAction抽象类定义。

例如我们可以继承DispatchAction来定义一个AccountAction,在当中集中管理一些与账号相关的操作,如下:

package com.fasttalk;
                                                                               
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.actions.*;
                                                                                
public class AccountAction extends DispatchAction {
    public ActionForward login(ActionMapping mapping,
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response)
    throws Exception {
        // login
相关的操作

        ......
    }
                                                                               
    public ActionForward logout(ActionMapping mapping,
                                ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response)
    throws Exception {
        // logout
相关的操作
        ......
    }

    public ActionForward method1(ActionMapping mapping,
                                ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response)
    throws Exception {
        // method1
相关的操作
        ......
    }

    .....
}
我们不再重新定义execute()方法,而是定义我们自己的login()、logout()等方法,
这些方法接收与execute()相同的参数,并且也传回ActionForward对象。

使用DispatchAction时,我们要在struts-config.xml定义:
       <ACTION
            path="/account"
            type="com.fasttalk.AccountAction"
            parameter="method"
            name="userForm">
            <FORWAR< span>
                
使用方法:
通过参数method= method1 来选择函数
<%
String dest = " account.do?method= method1";
response.sendRedirect(dest);
%>