strus2學習筆記

1、定義一個action需要繼承ActionSupport

    1.1、ActionSupport繼承了 Action, Validateable, ValidationAware, TextProvider, LocaleProvider接口.

Action提供了一些String常量,如:ERROR,INPUT,LOGIN,NONE,SUCCESS

Validateable定義了一個validate()方法,如果action繼承它,可以獲得這個方法

ValidationAware提供了判斷獲取錯誤和保存錯誤的方法:

 boolean hasActionMessages()
 void setFieldErrors(Map<String, List<String>> errorMap);
 Map<String, List<String>> getFieldErrors();
 void addActionError(String anErrorMessage);
 void addFieldError(String fieldName, String errorMessage);

TextProvider提供了獲取本地消息的方法String getText(String key, String defaultText)

 2、基本驗證

如果一個action繼承了ActionSupport並且繼承了默認棧則可以實現基本驗證

首先workflow攔截器會檢查action中是否實現了validate方法(通過Validateable接口暴露方法),實現了則運行validate方法,如果產生了錯誤,則會調用ValidationAware接口定義好的保存錯誤的方法,

validate方法沒有返回值,所以當該方法運行完之後,workflow攔截器會檢查驗證過程中是否產生了錯誤,如果產生了,則停止向下一個攔截器遞歸,返回input指定的page頁面

 protected String doIntercept(ActionInvocation invocation) throws Exception {
        Object action = invocation.getAction();

        if (action instanceof ValidationAware) {
            ValidationAware validationAwareAction = (ValidationAware) action;

            if (validationAwareAction.hasErrors()) {//判斷是否有錯誤
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Errors on action " + validationAwareAction + ", returning result name 'input'");
                }

                String resultName = inputResultName;

                if (action instanceof ValidationWorkflowAware) {
                    resultName = ((ValidationWorkflowAware) action).getInputResultName();
                }

                InputConfig annotation = action.getClass().getMethod(invocation.getProxy().getMethod(), new Class[0]).getAnnotation(InputConfig.class);
                if (annotation != null) {
                    if (!annotation.methodName().equals("")) {
                        Method method = action.getClass().getMethod(annotation.methodName());
                        resultName = (String) method.invoke(action);
                    } else {
                        resultName = annotation.resultName();
                    }
                }




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