用了一段时间ofbiz自带的form widgets工具,发现不是很好用。尤为是与前端配合开发的时候,表单的样式、效果受到了不少的限制。因而决定抛弃form widget,用freemarker。前端开发出来的效果和效率果真有了很大提交。可是存在一个问题,就是用freemarker写的表单提交如何作校验?和Struts不同,struts框架中自带了form的验证器。那么ofbiz除了form widget之外,有没有办法实现表单验证呢? 前端
答案就在ofbiz的service中。 java
由于ofbiz的逻辑层是一个一个的services,在给service的定义时,必需要给出传入参数和返回结果(参考services.xml)。以下service中定义了一个createProduct的服务。须要传入productId等参数。 框架
- <service name="createProduct" engine="java"
- location="com.openb2c.product.common.ProductServices"
- invoke="createProduct">
- <attribute name="productId" type="String" mode="IN"
- optional="false"></attribute>
- ......
- </service>
这里能够给每个attribute内加上这样一个标签:ide
- <attribute name="productId" type="String" mode="IN" optional="false">
- <type-validate class="org.ofbiz.base.util.UtilValidate "
- method="isNotEmpty ">
- <fail-message message="productId不能为空" />
- </type-validate>
- </attribute>
这个<type-validate>标签将会对attribute: productId进行校验。工具
校验的方法如上所见,装载class"org.ofbiz.base.util.UtilValidate ",这个class是ofbiz自带的一个验证工具,固然也能够写你本身适用的验证工具 。并调用class中的方法method"isNotEmpty"。这里运用了java的反射技术。fail-message是当验证不经过时,返回给服务调用者的错误信息。 spa
service会把全部的参数都验证一遍,如有多个参数不经过的话,会把全部的不经过信息都返回。 orm
至此,只要咱们提交表单时,把request指向一个service。(在controller.xml中定义request-map,request-map中定义<event type="service" invoke="createProduct"/>)。当service校验不经过时,就会把错误并错误信息一块儿返回。只要在request-map的response中定义service失败的页面跳转,便可把信息返回给用户。 xml
另外,我使用的ofbiz版本(opentaps 1.0使用的)对一个参数只支持一个validator,要支持一个属性多个validators的验证,只需简单的在ModelServiceReader(解释services.xml的工具)的方法addValidators方法中稍做修改便可。 blog
到此,ofbiz表单部分比较知足咱们OpenB2C项目的开发需求。前端UI用freemarker较快作出好的页面,而且能对表单作验证。开发