在Spring MVC體系里,已經(jīng)提供了bind(request,command)函數(shù)進行Bind and Validate工作。
但因為默認的bind()函數(shù)是拋出Servlet異常,而不是返回以數(shù)組形式保存錯誤信息的BindingResult對象供Controller處理 所以BaseController另外實現(xiàn)了一個bindObject函數(shù):
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對象,(另外一個方案是實現(xiàn)Category的PropertityEditor,并注冊,不過這太不實際了)并命令binder忽略這些已被手工綁定的field.
注意,如果不忽略,binder綁定時則很有可能出錯。
第4句增加validator。
第5句執(zhí)行Bind and Validate。
不過,我們一般會重載preBind()函數(shù)來完成1-3句的操作。逐一
而且springmodules+ common-validator已經(jīng)提供了默認的幾種Validator和在XML節(jié)點配置默認注入的框架,只有自己寫了特別的validator,并且不希望使用common-validator框架來定義時才像第四步那樣使用BaseController的addValidator函數(shù)加入新的validator。
2.Binder
一般由ServletRequestDataBinder完成Bind的工作。與其他框架自動綁定FormBean不同,Spring里需要手工調(diào)用Binder.
但因為日期格式不固定, Binder并沒有預先包含Date的Propertity Editor。 另外數(shù)字類的Editor默認不允許字符串為空,這些都需要初始化設置。
在Multi-action體系中,有initBinder()的callBack函數(shù):
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函數(shù)是getCommandName(),getCommandName將用于在頁面用<spring:bind>綁定錯誤信息時的標識,baseController默認定為首字母小寫的類名。
3.Validator
Validator的客戶端和服務器端方案用common validator和spring moudles里的集成 。
4.Bind and Validate出錯處理
Bind and Validate出錯,一般會重新跳回輸入頁面,在頁頭以如下代碼顯示錯誤信息,并重新綁定所有數(shù)據(jù):
<%@ 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
周銳 閱讀(442)
評論(0) 編輯 收藏 所屬分類:
Spring