DispatchAction类( org.apache.struts.actions.DispatchAction )提供了一种将所有相关功能分组为单个动作类的方法。 这是避免为每个函数创建单独的动作类的有用机制。
下载此Struts DispatchAction示例– Struts-DispatchAction-Example.zip
要实现此机制,您的操作类需要扩展org.apache.struts.actions.DispatchAction类,该操作类不需要像常规操作类一样实现execute()方法。 相反,DispatchAction类将基于传入的请求参数– method执行该方法 。 例如,如果参数为“ method = chinese”,则将执行chinese()方法。
例
动作类扩展了DispatchAction,并包含四个方法来将语言环境设置为Struts会话属性以进行本地化。
public class LanguageSelectAction extends DispatchAction{
public ActionForward chinese(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response)
throws Exception {
request.getSession().setAttribute(
Globals.LOCALE_KEY, Locale.SIMPLIFIED_CHINESE);
return mapping.findForward("success");
}
public ActionForward english(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response)
throws Exception {
request.getSession().setAttribute(
Globals.LOCALE_KEY, Locale.ENGLISH);
return mapping.findForward("success");
}
public ActionForward german(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response)
throws Exception {
request.getSession().setAttribute(
Globals.LOCALE_KEY, Locale.GERMAN);
return mapping.findForward("success");
}
public ActionForward france(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response)
throws Exception {
request.getSession().setAttribute(
Globals.LOCALE_KEY, Locale.FRANCE);
return mapping.findForward("success");
}
}
这个Struts html标记将执行chinese()方法。
page="/Locale.do?method=chinese">
此Struts html标记将执行english()方法。
page="/Locale.do?method=english">
该Struts html标记将执行german()方法。
page="/Locale.do?method=german">
此Struts html标记将执行france()方法。
page="/Locale.do?method=france">
标签: Struts
翻译自: https://mkyong.com/struts/struts-dispatchaction-example/