给WebWork2.2增加JavaScript客户端校验(二)

(接上文)

注:以下代码大部分来自WebWork 2.1.6对应的文件,非作者自己撰写.加入的代码需要import一些类,请自己导入.

修改UIBean.java

1.在evaluateParams方法中的最后一行代码, 

 evaluateExtraParams();

之前增加如下代码

//by scud start

if (canJSValidator() && ( form != null) ) {
    // register ScriptValiationAware validators for this UI tag with the form
    Boolean validate = (Boolean) form.getParameters().get("validate");

    if ((validate != null) && validate.booleanValue() && (form.getActionClass() != null) && (form.getActionName() != null) && name != null) {
        findScriptingValidators(form, (String) name, form.getActionClass(), null);
    }
}

//by scud end


2.增加一些方法,可以放在UIBean的最后

    //by scud start
   
    /**
     * Finds all ScriptValidationAware validators that apply to the field covered by this tag.
     *
     * @param formTag      the parent form tag this tag is in
     * @param fieldName    the name of the field to validate (used for error message key)
     * @param fieldClass   the Class of the object the field is for
     * @param propertyName the actual property name to get validator for; if null, fieldName is used
     */
    private void findScriptingValidators(Form formTag, String fieldName, Class fieldClass, String propertyName) {
        List validators = ActionValidatorManager.getValidators(fieldClass, formTag.getActionName());
        String name = fieldName;

        if (propertyName != null) {
            name = propertyName;
        }

        for (Iterator iterator = validators.iterator(); iterator.hasNext();) {
            Validator validator = (Validator) iterator.next();

            if (!(validator instanceof ScriptValidationAware)) {
                continue;
            }

            ValidatorContext validatorContext = new DelegatingValidatorContext(fieldClass);

            if (validator instanceof FieldValidator) {
                FieldValidator fieldValidator = (FieldValidator) validator;

                // JavaScriptVisitorFieldValidators must validate model, not action
                if (validator instanceof JavaScriptVisitorFieldValidator) {
                    JavaScriptVisitorFieldValidator visitorValidator = (JavaScriptVisitorFieldValidator) validator;
                    String propName = null;
                    boolean visit;

                    if (visitorValidator.getFieldName().equals("model") && ModelDriven.class.isAssignableFrom(fieldClass)) {
                        visit = true;
                    } else {
                        String baseName = name;
                        int idx = name.indexOf(".");

                        if (idx != -1) {
                            baseName = name.substring(0, idx);
                            propName = name.substring(idx + 1);
                        }

                        visit = baseName.equals(visitorValidator.getFieldName());
                    }

                    if (visit) {
                        Class realFieldClass = visitorValidator.getValidatedClass();

                        if (realFieldClass == null) {
                            for (Iterator iterator1 = getStack().getRoot().iterator(); iterator1.hasNext();) {
                                Object o = iterator1.next();
                                try {
                                    PropertyDescriptor pd =
                                            OgnlRuntime.getPropertyDescriptor(o.getClass(), visitorValidator.getFieldName());
                                    realFieldClass = pd.getPropertyType();
                                    break;
                                } catch (Throwable t) {
                                    // just keep trying
                                }
                            }
                        }

                        if (realFieldClass != null) {
                            if (visitorValidator.isAppendPrefix()) {
                                findScriptingValidators(formTag, visitorValidator.getFieldName() + "." + name, realFieldClass, propName);
                            } else {
                                findScriptingValidators(formTag, name, realFieldClass, propName);
                            }
                        } else {
                            LOG.warn("Cannot figure out class of visited object");
                        }
                    }
                } else if (fieldValidator.getFieldName().equals(name)) {
                    validator.setValidatorContext(validatorContext);
                    formTag.registerValidator((ScriptValidationAware) fieldValidator, new HashMap(getParameters()));
                }
            } else {
                validator.setValidatorContext(validatorContext);
                formTag.registerValidator((ScriptValidationAware) validator, new HashMap(getParameters()));
            }
        }
    }
   

    /**
     * will validator by javascript .
     *
     * @return true if set in webwork.properties,else false
     */
    public static boolean canJSValidator()
    {
        String propString = "jsvalidator";
        if(Configuration.isSet(propString))
        {
            return "true".equals(Configuration.getString(propString));
        }
       
        return false;
    }
   
    //by scud end


修改Form.java

1.增加一些字段

    //by scud start
    Class actionClass;
    String actionName;
   
    List fieldParameters;
    List fieldValidators;
   
    //by scud end

2.添加代码 在方法 evaluateExtraParams() 中

addParameter("namespace", namespace);

之前:

    //by scud start
   
    try {
        actionClass = ObjectFactory.getObjectFactory().getClassInstance(actionConfig.getClassName());
    } catch (ClassNotFoundException e) {
        // this is ok
    }
   
    actionName = action;
   
    //by scud end


3.在方法 evaluateExtraParams() 的最后增加:

        //by scud start
       
        if(canJSValidator())
        {
            if (fieldValidators != null) {
                StringBuffer js = new StringBuffer();
   
                // loop backwards so that the first elements are validated first
                for (int i = 0; i < fieldValidators.size(); i++) {
                    ScriptValidationAware sva = (ScriptValidationAware) fieldValidators.get(i);
                    Map params = (Map) fieldParameters.get(i);
                    js.append(sva.validationScript(params));
                    js.append('\n');
                }
   
                addParameter("javascriptValidation", js.toString());
            } else {
                addParameter("javascriptValidation", "// cannot find any applicable validators");
            }       
        }
       
        //by scud end


4.增加一些方法

    //by scud start
   
    public Class getActionClass() {
        return actionClass;
    }

    public String getActionName() {
        return actionName;
    }
   
    /**
     * Registers ScriptAware validators that should be called when the form is closed to output
     * necessary script.
     * <p />
     * Registration of validators is open until the first time the end of the tag is reached or
     * there will be duplicate validators if the tag is cached.
     */
    public void registerValidator(ScriptValidationAware sva, Map params) {
        if (fieldValidators == null) {
            fieldValidators = new ArrayList();
            fieldParameters = new ArrayList();
        }

        fieldValidators.add(sva);
        fieldParameters.add(params);
    }
   
    //by scud end



注意:在原有的Form.java里有一个小小的bug,参考 http://forums.opensymphony.com/thread.jspa?threadID=7390&tstart=0 ,在后续版本中应该会被修复.

相关代码如下:

    // if the id isn't specified, use the action name
    if (id == null) {
        id = action; //增加了这行
        addParameter("id", action);
    }


 
创造共用协议:署名,非商业,保持一致   除经特别注明外,本文章版权归JScud Develop团队或其作者所有.
署名,非商业用途,保持一致.   scud(飞云小侠)   JScud Develop

posted on 2005-10-03 14:37 Scud(飞云小侠) 阅读(1159) 评论(0)  编辑  收藏 所属分类: WEB


只有注册用户登录后才能发表评论。


网站导航:
 
<2005年10月>
2526272829301
2345678
9101112131415
16171819202122
23242526272829
303112345

导航

统计

公告

文章发布许可
创造共用协议:署名,非商业,保持一致

我的邮件
cnscud # gmail


常用链接

留言簿(15)

随笔分类(113)

随笔档案(103)

相册

友情链接

技术网站

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜