Struts 分发机制

Struts分发机制

简介

DispatchAction就是在struts-config中用parameter参数配置一个表单字段名,这个字段的值就是最终替代execute被调用的方法. 例如parameter="method"而request.getParameter("method")="save",其中"save"就是MethodName。struts的请求将根据parameter被分发到"save"或者"edit"或者什么。但是有一点,save()或者edit()等方法的声明和execute必须一模一样。

LookupDispatchAction继承DispatchAction, 用于对同一个页面上的多个submit按钮进行不同的响应。其原理是,首先用MessageResource将按钮的文本和资源文件的key相关联,例如button.save=保存;然后再复写getKeyMethodMap(), 将资源文件的key和MethodName对应起来, 例如map.put("button.save", "save"); 其配置方法和DispatchAction是一样的, 使用时要这么写:
<html:submit property="method">
  <bean:message key="button.save"/>
</html:submit>

LookupDispatchAction的使用

1) 类编写规范

BaseAction继承LookupDispatchAction,且必须实现方法protected Map getKeyMethodMap()。这个方法将构建资源key和方法名称对,放到Map里面返回。代码如下:

    /* (非 Javadoc)
     * @see org.apache.struts.actions.LookupDispatchAction#getKeyMethodMap()
     */
    protected Map getKeyMethodMap() {
        Map map = new HashMap();
        String pkg = this.getClass().getPackage().getName();
        ResourceBundle methods =
                ResourceBundle.getBundle(pkg + ".LookupMethods");

        Enumeration keys = methods.getKeys();
    
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            map.put(key, methods.getString(key));
        }    

        return map;
    }
2) 资源文件

这个例子中,将资源key和方法名称对放到资源文件LookupMethods.properties中。

资源文件LookupMethods.properties的内容如下:

button.edit=edit
button.delete=delete
......

然后,在struts的MessageResource使用的资源文件如 ApplicationResource.properties 中添加资源key的值:

button.edit=编辑
button.delete=删除
......

当然必须用ascii2native转换成unicode。

3) 页面编写

然后界面中就可以使用以下方式提交:

<html:submit property="method">
  <bean:message key="button.edit"/>
</html:submit>

或者

<html:submit property="method">
 
编辑
</html:submit>

4) 配置

method属性是指定的分发属性,在struts-config.xml中配置。action的配置应该加上parameter="method"来指定。如:

  <action  path="/customer/customer"  
                
type="com.demo.order.actions.CustomerAction"  
                
name="customerForm"  
                
parameter="method"  
                
input="add"
                unknown="false"
                validate="true"
                >
            <forward  name="view"  path="model.customer.view">
            </forward>
            <forward  name="add"  path="model.customer.add">
            </forward>
            <forward  name="list"  path="model.customer.list">
            </forward>

        </action>

配置好后,按上面所描述的方式提交,BaseAction类将分几步执行:

  1. 从配置中取得parameter属性的值,这里为“method”。
  2. 再按method找到提交的属性中取得method属性的值,这里为“编辑”。
  3. 从MessageResource使用的资源文件中取得“编辑”对应的key,这里为“button.edit”。
  4. 从getKeyMethodMap方法返回的Map中取得改key值对应的方法名称,这里为“edit”。
  5. 调用BaseAction类的方法edit。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值