DispatchAction

来源:互联网 发布:少数民族语言翻译软件 编辑:程序博客网 时间:2024/05/24 06:31

DispatchAction

一个Action中会有许多不同的操作,每个操作被封装成独立的方法。这些操作会以一个参数如actionmethodstatus来区分。

struts 1.x 内置了分发器DispatchAction,只需继承DispatchAction类,并指定按哪个参数进行分发。

public class UseBeanAction extends DispatchAction {

    public ActionForward add(ActionMapping mapping, ActionForm form,

           HttpServletRequest request, HttpServletResponse response) throws IOException {

       UseBeanForm useBeanForm = (UseBeanForm) form;

       response.setCharacterEncoding("UTF-8") ;

           Person person = useBeanForm.getPerson() ;

           response.getWriter().println("person.account:"+person.getAccount()) ;

           response.getWriter().println("<br/n>") ;

           response.getWriter().println("person.name:"+person.getName()) ;

           response.getWriter().println("<br/n>") ;

           response.getWriter().println("执行了add方法。。。。") ;

           return null;

    }

    public ActionForward list(ActionMapping mapping, ActionForm form,

           HttpServletRequest request, HttpServletResponse response) throws IOException {

       UseBeanForm useBeanForm = (UseBeanForm) form;

       response.setCharacterEncoding("UTF-8") ;

           Person person = useBeanForm.getPerson() ;

           response.getWriter().println("person.account:"+person.getAccount()) ;

           response.getWriter().println("<br/n>") ;

           response.getWriter().println("person.name:"+person.getName()) ;

           response.getWriter().println("<br/n>") ;

           response.getWriter().println("执行了list方法。。。。") ;

           return null;

    }

}

注意,execute()方法要执行super.execute(),因为父类的execute()实现了分发。如果覆盖了此方法,分发器就失效了。所以可以将Action中的execute()方法删除。

DispatchAction要知道按哪个参数进行分发。分发器的参数parameter设置在struts-config.xmlAction配置中。

<action

      attribute="useBeanForm"

      input="/useBean.jsp"

      name="useBeanForm"

      parameter="status"

      path="/useBean"

      scope="request"

      type="com.hym.struts.action.UseBeanAction" />

在输入页面中给分发器的参数赋值,指定要分发的方法。

    <html:form action="/useBean.do?status=list" method="post">

    账号:<html:text property="person.account"></html:text><br/>

    姓名:<html:password property="person.name"></html:password><br/>

    <html:submit value="提交"></html:submit>

    <html:reset value="重置"></html:reset>

                     </html:form>