且行且珍惜

java road

常用链接

统计

最新评论

关于struts 中 LazyValidatorForm 模式的学习

struts 中LazyValidatorForm特别适用于FormBean中并不包含POJO商业对象所有属性的情况,因为通常项目里都属于这种情况,所以springside默认使用lazyValidatorForm. 
    比如User对象 有 id,name,status三个属性,而form表单中只有id和name两个input框,如果使用其他模式,直接把user 作为 form bean,  user对象的status因为没设值,将为null,  copy 到作为商业对象的user时,就会以null覆盖原值。而lazyBean就没有这个问题,如果form中没有status属性,它不会将它copy给商业对象。
    实际工程中将封装beanUtils中的copyProperties方法,用于将form中的属性绑定到实体对象中,
    /**
     * 将FormBean中的内容通过BeanUtils的copyProperties()绑定到Object中.
     * 因为BeanUtils中两个参数的顺序很容易搞错,因此封装此函数.
     */
    protected void bindEntity(ActionForm form, Object object)
    {
        if (form != null)
        {
            try
            {
                BeanUtils.copyProperties(object, form);
            }
            catch (Exception e)
            {
                ReflectionUtils.handleReflectionException(e);
            }
        }
    }
注意实体对象被自动绑定,默认Integer id 在空值时会被赋值为0,需要增加converter,让其默认为null,虽然也可以在web.xml里进行相关配置,但还是在基类里配置了比较安全。在工程中可以这样实现
 /**
     * 设置Struts 中数字<->字符串转换,字符串为空值时,数字默认为null,而不是0.
     * 也可以在web.xml中设置struts的参数达到相同效果,在这里设置可以防止用户漏设web.xml.
     */
    public static void registConverter()
    {
        ConvertUtils.register(new StringConvert("yyyy-MM-dd"), String.class);
        ConvertUtils.register(new IntegerConverter(null), Integer.class);
        ConvertUtils.register(new LongConverter(null), Long.class);
        ConvertUtils.register(new FloatConverter(null), Float.class);
        ConvertUtils.register(new DoubleConverter(null), Double.class);
        ConvertUtils.register(new DateConvert("yyyy-MM-dd"), Date.class);
    }

将属性绑定过程中的一些空默认值修改为null

posted on 2008-08-05 12:15 jws-21 阅读(1404) 评论(0)  编辑  收藏


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


网站导航: