讀JPetStore有感,靈活使用框架....

Struts想必大家已經用爛了把。。。^_^
今天無意中看了一點JPetStore的源代碼,發覺他的一些
用法很值得討論。。
JPetStore是1個完全的使用OpenSource的demo,
使用了Struts+IBATiS嘿嘿,以前不是有
j2ee版本的PetStore的demo嗎?^_^

JPetStore的設計令我眼前一亮的居然只使用了1個Action,注意不是ActionServlet,當然
Struts當然只使用1個前置控制器

關鍵代碼
if (form != null) {

        // Explicit Method Mapping
        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);
          }
        }

        // Path Based Method Mapping
        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);
              }
            }
     
這是這個BeanAction的關鍵代碼,當然這個BeanAction是繼承Action的,和普通的Action沒什麼2樣
這也是所有的請求所調用的Action....Cool....

這時要先說說JPetStore裏的ActionForm的設計,在JPetStore裏Form取名爲XXXBean,咋1看很令人奇怪..
仔細看,每個具體的XXXBean都繼承了一個BaseBean,而這個BaseBean則繼承了ActionForm,而這個
XXXBean引用了domain域對象(與數據庫字段是對應的),同時,在XXXBean裏添加了調用DAO的方法,例如
Insert,update等操作,成了1個名副其實的BO,同時,這些方法都是無參的,因爲使用的參數都可以從
Bean自生的字段取得,同是這也是關鍵的部分^_^

來看一段Struts-config.xml裏配置
<action path="/shop/viewItem" type="com.ibatis.struts.BeanAction"
      name="catalogBean" scope="session"
      validate="false" input="/catalog/Product.jsp">
      <forward name="success" path="/catalog/Item.jsp"/>
</action>

奇妙的地方在於,這個path的viewItem這部分是catalogBean裏的一個方法名,這時你可以回頭去看
這個BeanAction,他使用反射的原理,通過Form(其實成了1個BO)和 URL來定位調用的方法。

寫了1大段,^_^,感覺到靈活運用框架是多麼重要,不要拘泥與某些固定的用法....

DEMO的主頁,有興趣的朋友可以去看看
http://www.ibatis.com/jpetstore/jpetstore.html

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章