Monday, March 26, 2007

 

Paper Note: FormCreationAspect.aj

原本在Execution Code裡面需要跟使用者取得資料時
會產生一個Form物件
並且把一些跟目前Activity有關的資料塞進去這個Form中
如此才能夠讓Form正確地submit回來


public class ActivityExecutionCode extends ActivityExecutionCode {
   public void call(Message reqMsg) {
      ...
      Form form = new Form("Activity Form");
      form.add(new HiddenField("action", "FormSubmit"));
      form.add(new HiddenField("pid", reqMsg.get("pid")));
      form.add(new HiddenField("aName", reqMsg.get("aName")));
      form.add(new HiddenField("taskId", reqMsg.get("taskId")));
  
      form.add(new Label("message", "Message"));
      form.add(new TextField("message", ""));
      form.add(new LineBreak());
      form.add(new Button(Button.ButtonType.SUBMIT, "Send"));

      Message result = form.submit();
      String message = result.get("message");
      ...
   }
}

但其實我們不想讓寫Execution Code的設計者管這些其實跟本身Execution Code邏輯無關的東西
所以我們用FormCreationAspect來讓它自動塞入資料


public aspect FormCreationAspect {
   pointcut formCreation(Form form): initialization(Form.new(String)) && target(form);

   pointcut activityCall(Message reqMsg): 
      execution(public void ActivityExecutionCode+.call(Message)) && args(reqMsg);

   after(Form form, Message reqMsg):
    formCreation(form) && cflowbelow(activityCall(reqMsg)){
      // action=FormSubmit
      form.add(new HiddenField("action", "FormSubmit"));

      // pid={pid}
      String pidString = reqMsg.get("pid");
      if (!ParamUtil.noValue(pidString)) {
         Long pid = Long.parseLong(pidString);
         form.add(new HiddenField("pid", "" + pid));
      }

      // aName={aName}
      String aName = reqMsg.get("aName");
      if (!ParamUtil.noValue(aName)) {
         form.add(new HiddenField("aName", aName));
      }

      // taskId={taskId}
      String taskId = reqMsg.get("taskId");
      if (!ParamUtil.noValue(taskId)) {
         form.add(new HiddenField("taskId", taskId));
      }
   }
}

原本的Execution Code就變成下面這樣
少了原本塞資料的四行程式碼!


public class ActivityExecutionCode extends ActivityExecutionCode {
   public void call(Message reqMsg) {
      ...
      Form form = new Form("Activity Form");
  
      form.add(new Label("message", "Message"));
      form.add(new TextField("message", ""));
      form.add(new LineBreak());
      form.add(new Button(Button.ButtonType.SUBMIT, "Send"));

      Message result = form.submit();
      String message = result.get("message");
      ...
   }
}

Labels: , , ,


Comments: Post a Comment



<< Home