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类将分几步执行:
- 从配置中取得parameter属性的值,这里为“method”。
- 再按method找到提交的属性中取得method属性的值,这里为“编辑”。
- 从MessageResource使用的资源文件中取得“编辑”对应的key,这里为“button.edit”。
- 从getKeyMethodMap方法返回的Map中取得改key值对应的方法名称,这里为“edit”。
- 调用BaseAction类的方法edit。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步