看了这个struts+ibatis的例子,感觉它的设计思想很不错.和以前的jpetstore的模式有很大变化.
变化最明显的就是他只定义了一个BeanAction, (也只有一个BaseBean,其他的form bean都继承自BaseBean),它将以前的action都定义到了form bean中,这样form bean就不在只是处理数据这么简单.BeanAction中采用反射机制,来对应调用form bean中的action.这样就简化了BeanAction的处理.在配置文件中主要有三种调用action的方式:
1.URL Pattern
<ccid_code></ccid_code><action path="/shop/viewOrder" type="com.ibatis.struts.BeanAction" name="orderBean" scope="session" validate="false"> <forward name="success" path="/order/ViewOrder.jsp"/> </action> |
此种方式表示,控制将被转发到"orderBean"这个form bean对象 的"viewOrder"方法(行为)来处理。方法名取"path"参数的以"/"分隔的最后一部分。
它对应于BeanAction中的这部分代码:
if (method == null && !"*".equals(methodName)) {
methodName = mapping.getPath();
if (methodName.length() > 1) {
int slash = methodName.lastIndexOf("/") + 1;
methodName = methodName.substring(slash);
if (methodName.length() > 0) {
try {
method = form.getClass().getMethod(methodName, null);
forward = (String) method.invoke(form, null);
} catch (Exception e) {
throw new BeanActionException("Error dispatching bean action via URL pattern ('" + methodName + "'). Cause: " + e, e);
}
}
}
}
是通过path来取得要调用的action函数.
2.Method Parameter
<ccid_code></ccid_code><action path="/shop/viewOrder" type="com.ibatis.struts.BeanAction" name="orderBean" parameter="viewOrder" scope="session" validate="false"> <forward name="success" path="/order/ViewOrder.jsp"/> </action> |
此种方式表示,控制将被转发到"orderBean"这个form bean对象的"viewOrder"方法(行为)来处理。配置中的"parameter"参数表示form bean类上的方法。"parameter"参数优先于"path"参数。
它对应与BeanAction中的:
Method method = null;
String methodName = mapping.getParameter();
if (methodName != null && !"*".equals(methodName)) {
try {
method = form.getClass().getMethod(methodName, null);
forward = (String) method.invoke(form, null);
} catch (Exception e) {
throw new BeanActionException("Error dispatching bean action via method parameter ('" + methodName + "'). Cause: " + e, e);
}
}
通过paramater来调用对应的action函数
3.No Method call
<ccid_code></ccid_code><action path="/shop/viewOrder" type="com.ibatis.struts.BeanAction" name="orderBean" parameter="*" scope="session" validate="false"> <forward name="success" path="/order/ViewOrder.jsp"/> </action> |
此种方式表示,form bean上没有任何方法被调用。如果存在"name"属性,则struts把表单参数等数据填充到form bean对象后,把控制转发到"success"。否则,如果name为空,则直接转发控制到"success"。
这种parameter值为*的不调用任何action函数,有name属性则填充数据然后success.没有则直接success.
当然若name,parameter都没有则直接success.