天天看點

關于webwork中continuation用法的說明

  • 目的:continuation的出現,替代了通過session或者隐藏參數儲存資料的方式,它是使用java語言本身的特性來控制狀态
  • 目前發展狀況:目前我使用的是webwork2.2.7版本,在其版本中明确說明,目前該功能還不成熟,目前建議在大型系統中不要使用該功能。
  • 其他限制條件:在ExecuteAndWait 和Token攔截器中,不能使用continuaction,因為ExecuteAndWait和Token都會限制同一個Session的請求次數, 也就是說他們不"期望"看到相同的請求
  • 用法介紹

a)類必須繼承ActionSupport并且實作Preparable接口

b)在execute方法中,必須調用父類的pause方法。pause方法隻能在execute方法中調用。

c)在prepare方法中,必須要調用父類的clearErrorsAndMessages();方法。其目的是,清楚上次請求後産生的field errors 和action errors,如果不清楚,會産生意想不到的錯誤。以下是webwork中關于這點的原始解釋:// We clear the error message state before the action.That is because with continuations, the original (or cloned) action is being executed, which will still have the old errors and potentially cause problems,such as with the workflow interceptor

d)在webwork.propeties配置檔案中,一定要定義webwork.continuations.package=包,其目的是告訴webwork,那個包将會使用到continuation屬性

  •  原理闡述
使用continuations特性必須由WebWork管理流程狀态, 是以, 這要求應用程式必須将流程的ID告知WebWork.。WebWork使用一個名為 continue 的參數為流程中的每一次請求提供一個唯一id來做到這一點.。如果使用URL或Form标簽來産生URL連結, continue 參數将會自動生産。 如果沒有使用這些标簽, continuations不會正常工作。當你送出action的時候,使用get方法,那麼将會在位址欄中看到這個參數:__continue=b1683b46f8cade05eccbbb39d2c2b8ac,這個參數是通過webwork自己生成和維護的。
  • 示例代碼,配置檔案省略

public class PauseTestAction extends ActionSupport implements Preparable {

    private static final Log LOG = LogFactory.getLog(PauseTestAction.class);

    private int guess;

    public void prepare() throws Exception {

        // We clear the error message state before the action.

        // That is because with continuations, the original (or cloned) action is being

        //  executed, which will still have the old errors and potentially cause problems,

        //  such as with the workflow interceptor

        clearErrorsAndMessages();

    }

    public int getGuess() {

        return guess;

    }

    public void setGuess(int guess) {

        this.guess = guess;

    }

    public String execute() throws Exception {

        int answer = new Random().nextInt(100);

        int tries = 5;

        while (answer != guess && tries > 0) {

            pause(Action.SUCCESS);

            if (guess > answer) {

                addFieldError("guess", "Too high!");

            } else if (guess < answer) {

                addFieldError("guess", "Too low!");

            }

            tries--;

        }

        if (answer == guess) {

            addActionMessage("You got it!");

        } else {

            addActionMessage("You ran out of tries, the answer was " + answer);

        }

        return Action.SUCCESS;

    }