Struts2(3):Action介面和ActionSupport基類

來源:互聯網
上載者:User

為了讓使用者開發的Action類更規範,Struts2提供了一個Action介面,這個介面定義了Struts2的Action處理類應該實現的規範。下面是Action介面的源碼:

public interface Action {     public static final String ERROR="error";     public static final String INPUT="input";     public static final String LOGIN="login";     public static final String NONE="none";     public static final String SUCCESS="success";     public String execute( ) throws Exception;}

上面的Action介面裡只定義了一個execute方法,該介面的規範規定了Action類應該包含一個execute方法,該方法返回一個字串。除此之外,該介面還定義了5個字串常量,它們的作用是統一execute方法的傳回值。例如當Action類處理使用者請求成功後,有人喜歡返回welcome字串,有人喜歡返回success字串......這樣不利於項目的統一管理。Action介面定義了如上5個字串常量,分別代表了特定的含義。當然如果開發人員依然希望使用特定的字串作為邏輯視圖名,依然可以返回自己的視圖名。

另外,Struts2為Action介面提供了一個實作類別:ActionSupport

public class ActionSupport implements Action, Validateable, ValidationAware,     TextProvider, LocaleProvider, Serializable {    protected static Logger LOG = LoggerFactory.getLogger(ActionSupport.class);    private final transient TextProvider textProvider =             new TextProviderFactory().createInstance(getClass(), this);    private final ValidationAwareSupport validationAware = new ValidationAwareSupport();    public void setActionErrors(Collection<String> errorMessages) {        validationAware.setActionErrors(errorMessages);    }    public Collection<String> getActionErrors() {        return validationAware.getActionErrors();    }    public void setActionMessages(Collection<String> messages) {        validationAware.setActionMessages(messages);    }    public Collection<String> getActionMessages() {        return validationAware.getActionMessages();    }    /**     * @deprecated Use {@link #getActionErrors()}.     */    @Deprecated public Collection<String> getErrorMessages() {        return getActionErrors();    }    /**     * @deprecated Use {@link #getFieldErrors()}.     */    @Deprecated public Map<String, List<String>> getErrors() {        return getFieldErrors();    }    public void setFieldErrors(Map<String, List<String>> errorMap) {        validationAware.setFieldErrors(errorMap);    }    public Map<String, List<String>> getFieldErrors() {        return validationAware.getFieldErrors();    }    public Locale getLocale() {        ActionContext ctx = ActionContext.getContext();        if (ctx != null) {            return ctx.getLocale();        } else {            LOG.debug("Action context not initialized");            return null;        }    }    public boolean hasKey(String key) {        return textProvider.hasKey(key);    }    public String getText(String aTextName) {        return textProvider.getText(aTextName);    }    public String getText(String aTextName, String defaultValue) {        return textProvider.getText(aTextName, defaultValue);    }    public String getText(String aTextName, String defaultValue, String obj) {        return textProvider.getText(aTextName, defaultValue, obj);    }    public String getText(String aTextName, List<Object> args) {        return textProvider.getText(aTextName, args);    }    public String getText(String key, String[] args) {        return textProvider.getText(key, args);    }    public String getText(String aTextName, String defaultValue, List<Object> args) {        return textProvider.getText(aTextName, defaultValue, args);    }    public String getText(String key, String defaultValue, String[] args) {        return textProvider.getText(key, defaultValue, args);    }    public String getText(String key, String defaultValue, List<Object> args,                          ValueStack stack) {        return textProvider.getText(key, defaultValue, args, stack);    }    public String getText(String key, String defaultValue, String[] args,                          ValueStack stack) {        return textProvider.getText(key, defaultValue, args, stack);    }    public ResourceBundle getTexts() {        return textProvider.getTexts();    }    public ResourceBundle getTexts(String aBundleName) {        return textProvider.getTexts(aBundleName);    }    public void addActionError(String anErrorMessage) {        validationAware.addActionError(anErrorMessage);    }    public void addActionMessage(String aMessage) {        validationAware.addActionMessage(aMessage);    }    public void addFieldError(String fieldName, String errorMessage) {        validationAware.addFieldError(fieldName, errorMessage);    }    public String input() throws Exception {        return INPUT;    }    public String doDefault() throws Exception {        return SUCCESS;    }    /**     * A default implementation that does nothing an returns "success".     * <p/>     * Subclasses should override this method to provide their business logic.     * <p/>     * See also {@link com.opensymphony.xwork2.Action#execute()}.     *     * @return returns {@link #SUCCESS}     * @throws Exception can be thrown by subclasses.     */    public String execute() throws Exception {        return SUCCESS;    }    public boolean hasActionErrors() {        return validationAware.hasActionErrors();    }    public boolean hasActionMessages() {        return validationAware.hasActionMessages();    }    public boolean hasErrors() {        return validationAware.hasErrors();    }    public boolean hasFieldErrors() {        return validationAware.hasFieldErrors();    }    /**     * Clears field errors. Useful for Continuations and other situations     * where you might want to clear parts of the state on the same action.     */    public void clearFieldErrors() {        validationAware.clearFieldErrors();    }    /**     * Clears action errors. Useful for Continuations and other situations     * where you might want to clear parts of the state on the same action.     */    public void clearActionErrors() {        validationAware.clearActionErrors();    }    /**     * Clears messages. Useful for Continuations and other situations     * where you might want to clear parts of the state on the same action.     */    public void clearMessages() {        validationAware.clearMessages();    }    /**     * Clears all errors. Useful for Continuations and other situations     * where you might want to clear parts of the state on the same action.     */    public void clearErrors() {        validationAware.clearErrors();    }    /**     * Clears all errors and messages. Useful for Continuations and other situations     * where you might want to clear parts of the state on the same action.     */    public void clearErrorsAndMessages() {        validationAware.clearErrorsAndMessages();    }    /**     * A default implementation that validates nothing.     * Subclasses should override this method to provide validations.     */    public void validate() {    }    @Override public Object clone() throws CloneNotSupportedException {        return super.clone();    }    /**     * <!-- START SNIPPET: pause-method -->     * Stops the action invocation immediately (by throwing a PauseException)      * and causes the action invocation to return     * the specified result, such as {@link #SUCCESS}, {@link #INPUT}, etc.     * <p/>     * <p/>     * The next time this action is invoked (and using the same continuation ID),     * the method will resume immediately     * after where this method was called, with the entire call stack      * in the execute method restored.     * <p/>     * <p/>     * Note: this method can <b>only</b> be called      * within the {@link #execute()} method.     * <!-- END SNIPPET: pause-method -->     *     * @param result the result to return - the same type of      * return value in the {@link #execute()} method.     */    public void pause(String result) {    }}

ActionSupport是一個預設的Action實作類別,該類裡已經提供了許多預設方法,這些預設方法包括擷取國際化資訊的方法,資料校正的方法,預設的處理使用者請求的方法等。實際上,ActionSupport類是Struts2預設的Action處理類,如果讓開發人員的Action類繼承ActionSupport,會大大簡化Action的開發。所以實際開發中Action一般都選擇繼承ActionSupport基類。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.