posts - 431,  comments - 344,  trackbacks - 0

在Spring MVC体系里,已经提供了bind(request,command)函数进行Bind and Validate工作。
  但因为默认的bind()函数是抛出Servlet异常,而不是返回以数组形式保存错误信息的BindingResult对象供Controller处理 所以BaseController另外实现了一个bindObject函数:

BindException  bindObject(ServletRequest request, Object command)
1.Bind And Validate的完整使用代码:
     public BindingResult bindBook(HttpServletRequest request, Book book) throws Exception
    {
 Integer category_id = new Integer(request.getParameter("category.id"));
        book.setCategory(bookManager.getCategory(category_id));
        binder.setDisallowedFields(new String[]{"category"});
addValidator(new BookValiator());
        return bindObject(request, book);
}
  其中第1-3句是绑定不能自动绑定的Category对象,(另外一个方案是实现Category的PropertityEditor,并注册,不过这太不实际了)并命令binder忽略这些已被手工绑定的field.
       注意,如果不忽略,binder绑定时则很有可能出错。

  第4句增加validator。

  第5句执行Bind and Validate。

不过,我们一般会重载preBind()函数来完成1-3句的操作。逐一
     而且springmodules+ common-validator已经提供了默认的几种Validator和在XML节点配置默认注入的框架,只有自己写了特别的validator,并且不希望使用common-validator框架来定义时才像第四步那样使用BaseController的addValidator函数加入新的validator。

2.Binder
     一般由ServletRequestDataBinder完成Bind的工作。与其他框架自动绑定FormBean不同,Spring里需要手工调用Binder.

     但因为日期格式不固定, Binder并没有预先包含Date的Propertity Editor。 另外数字类的Editor默认不允许字符串为空,这些都需要初始化设置。

     在Multi-action体系中,有initBinder()的callBack函数:

        SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtil.getDatePattern());
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(Integer.class, new CustomNumberEditor(Integer.class, true));
        binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, true));
   createBinder的另一个callBack函数是getCommandName(),getCommandName将用于在页面用<spring:bind>绑定错误信息时的标识,baseController默认定为首字母小写的类名。

 

3.Validator
     Validator的客户端和服务器端方案用common validator和spring moudles里的集成 。

 

4.Bind and Validate出错处理
    Bind and Validate出错,一般会重新跳回输入页面,在页头以如下代码显示错误信息,并重新绑定所有数据:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>


<c:iftest="${book!=null}">
    <spring:bind path="book.*">
        <c:if test="${not empty status.errorMessages}"><  BR>            <div class="error">
                <c:forEach var="error" items="${status.errorMessages}">
                    ${error}<br/>
                </c:forEach>
            </div>
        </c:if>
    </spring:bind>
</c:if>

 

posted on 2009-01-09 23:05 周锐 阅读(424) 评论(0)  编辑  收藏 所属分类: Spring

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


网站导航: