Struts分发机制

Posted on 2006-01-06 09:40 Computerboy 阅读(362) 评论(0)  编辑  收藏
简介 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是一样的, 使用时要这么写: 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) 页面编写然后界面中就可以使用以下方式提交: 或者 编辑

4) 配置 method属性是指定的分发属性,在struts-config.xml中配置。action的配置应该加上parameter="method"来指定。
如:   配置好后,按上面所描述的方式提交,BaseAction类将分几步执行:
从配置中取得parameter属性的值,这里为“method”。 再按method找到提交的属性中取得method属性的值,这里为“编辑”。
从MessageResource使用的资源文件中取得“编辑”对应的key,这里为“button.edit”。
从getKeyMethodMap方法返回的Map中取得改key值对应的方法名称,这里为“edit”。 调用BaseAction类的方法edit。

只有注册用户登录后才能发表评论。


网站导航:
 

posts - 40, comments - 39, trackbacks - 0, articles - 0

Copyright © Computerboy