- 论坛徽章:
- 0
|
4.如何使用已经定义的 Schema
如何使用已经定义的 Schema
Ofbiz 遵循 MVC 的设计模式,在 View 端,即 JSP 端主要使用 Ofbiz 定义的 Tag 来显示或
提取数据,Control 是一个 Controller Servlet,我们在 Controller Servlet 的 URI mapping
配置文件中定义各 URL 应该指向什么程序,这样,通过这个 mapping 配置文件,可以保证我们各个页面
及具体处理程序之间的独立性,例我们可以通过修改这个配置文件就可以改变某个 Form 的 Post Action
的 URL,而不需要修改实际的 HTML 或 JSP 代码。
Ofbiz 中定义了 Regions 的概念,即将一个 HTML 页面分成几个区域,像 Top, Left, Right, Main
等,通过这些 Regions 我们可以方便的组合 UI 界面,并且可以方便改变各部分所处的位置,如我们可以
把菜单很容易的从上方移到下方,只需要改变一个配置文件。Regions 类似于 HTML 中的 Frame,但它是
通过一个页面来组合界面,Frame 是通过几个页面显示在不同的帧中,Frame 的控制比较复杂,而且需要
改变相关的程序。
在 Ofbiz 中,我们可以直接在 JSP 中操作 Schema 定义的 Object,即我们刚定义的 StudyCustomer,
示例如下:
<%@ taglib uri="ofbizTags" prefix="ofbiz" %>
<%@ page import="java.util.*" %>
<%@ page import="org.ofbiz.core.util.*, org.ofbiz.core.pseudotag.*" %>
<%@ page import="org.ofbiz.core.entity.*" %>
<jsp:useBean id="delegator" type="org.ofbiz.core.entity.GenericDelegator" scope="request" />
<jsp:useBean id="security" type="org.ofbiz.core.security.Security" scope="request" />
<%if(security.hasEntityPermission("PARTYMGR", "_VIEW", session)) {%>
<%
try {
delegator.create("StudyCustomer",
UtilMisc.toMap("customerId","1","customerName","Cust1","customerNote","Customer Note 1"));
Iterator custs =
UtilMisc.toIterator(delegator.findAll("StudyCustomer",UtilMisc.toList("customerId","customerName","customerNote")));
while(custs.hasNext())
{
GenericValue cust = (GenericValue)custs.next();
out.println(cust.getString("customerId"));
out.println(cust.getString("customerName"));
out.println(cust.getString("customerNote"));
}
} catch(Exception e)
{
out.println(e.getMessage());
}
%>
<%}else{%>
<h3>You do not have permission to view this page. ("PARTYMGR_VIEW" or "PARTYMGR_ADMIN" needed)</h3>
<%}%>
这段程序挺容易理解,先是通过 delegator 创建一个 Object,该 Object 将会由 Ofbiz 自动同步到
数据库中。然后通过 delegator 的 findAll 取到所有已保存的 Object,最后通过一个 Iterator 对象
显示出来。
这个程序起名为 testofbiz.jsp,为简单起见,我们放到 Ofbiz 已有的一个 Webapp 的目录下,放到
c:\ofbiz\ofbiz\partymgr\webapp\party 目录下。然后我们需要修改两个配置文件:controller.xml
和 regions.xml,这两个文件就是我们上面提到的 mapping 和 regions 配置文件。
这两个文件都在:c:\ofbiz\ofbiz\partymgr\webapp\WEB-INF 下,在 controller.xml 中加入下面
<request-map uri="testofbiz">
<description>Test Ofbiz</description>
<security https="false" auth="false"/>
<response name="success" type="view" value="testofbiz"/>
</request-map>
和
<view-map name="testofbiz" type="region"/>
加入位置请参照 controller.xml 中已经有的配置。在 regions.xml 中加入:
<define id='testofbiz' region='MAIN_REGION'>
<put section='title'>Test Ofbiz</put>
<put section='content' content='/party/testofbiz.jsp'/>
</define>
具体加入位置请参考已有的配置。
配置完后,重新启动 ofbiz,然后访问 URL:
http://localhost:8080/partymgr/control/testofbiz
由于我们在 testofbiz.jsp 程序中使用了 Ofbiz 的安全控制机制,系统会提示现在没有访问
权限,需要登录,点击右边的“Login” 用 admin/ofbiz 登录后会看到我们程序 testofbiz.jsp
的运行结果。如果需要增加新记录,请修改
UtilMisc.toMap("customerId","1","customerName","Cust1","customerNote","Customer Note 1"));
中的各个段的值,然后再访问 http://localhost:8080/partymgr/control/testofbiz,如果不修改
而直接访问那个 URL 时,系统会提示 Primary key 冲突。
5.按照显示与逻辑分离的原则使用 Schema:
上篇讲了如何在 JSP 中使用创建的 Schema 对象,这次我们来讲述一下如何把程序
逻辑放到 JavaBeans 中,把显示处理放到 JSP 中,并使用 controller.xml 将两
部分整合起来。
首先我们来创建一个 JavaBeans,来完成Add/Get/Delete/Update Schema 对象
的操作,程序文件名为 TestOfbiz.java,放置在
c:\ofbiz\ofbiz\testOfbiz\com\geeyo\ofbiz 目录下, 具体程序如下:
>=================================================================
package com.geeyo.ofbiz;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.net.*;
import org.ofbiz.core.util.*;
import org.ofbiz.core.entity.*;
import org.ofbiz.core.service.*;
import org.ofbiz.core.security.*;
import org.ofbiz.core.stats.*;
public class TestOfbiz
{
public static void main(String[] args)
throws Exception
{
GenericDelegator delegator = GenericDelegator.getGenericDelegator("default");
delegator.create("StudyCustomer",UtilMisc.toMap("customerId","3","customerName","Kane3","customerNote","This is test customer.3"));
Iterator custs = UtilMisc.toIterator(delegator.findAll("StudyCustomer",UtilMisc.toList("customerId","customerName","customerNote")));
while(custs.hasNext())
{
GenericValue cust = (GenericValue)custs.next();
System.out.println(cust.getString("customerId"));
System.out.println(cust.getString("customerName"));
System.out.println(cust.getString("customerNote"));
}
}
public static String createNewRecord(HttpServletRequest request, HttpServletResponse response)
throws Exception
{
Map paras = UtilMisc.getParameterMap(request);
GenericDelegator delegator = GenericDelegator.getGenericDelegator("default");
delegator.create("StudyCustomer",paras);
return "success";
}
public static String lookAllRecords(HttpServletRequest request, HttpServletResponse response)
throws Exception
{
GenericDelegator delegator = GenericDelegator.getGenericDelegator("default");
Iterator custs = UtilMisc.toIterator(delegator.findAll("StudyCustomer",UtilMisc.toList("customerId","customerName","customerNote")));
Collection col = new ArrayList();
while(custs.hasNext())
{
GenericValue cust = (GenericValue)custs.next();
col.add(cust);
}
request.getSession().setAttribute("search_results",col);
return "success";
}
public static String findRecord(HttpServletRequest request, HttpServletResponse response)
throws Exception
{
String id = (String)request.getParameter("customerId");
GenericDelegator delegator = GenericDelegator.getGenericDelegator("default");
try {
GenericValue cust = delegator.findByPrimaryKey("StudyCustomer",UtilMisc.toMap("customerId",id));
request.getSession().setAttribute("edit_cust",cust);
} catch (GenericEntityException gee) {
Debug.logWarning(gee);
}
return "success";
}
public static String updateRecord(HttpServletRequest request, HttpServletResponse response)
throws Exception
{
Map paras = UtilMisc.getParameterMap(request);
GenericDelegator delegator = GenericDelegator.getGenericDelegator("default");
GenericValue cust = delegator.findByPrimaryKey("StudyCustomer",UtilMisc.toMap("customerId",paras.get("customerId")));
cust.setNonPKFields(paras);
cust.store();
request.getSession().setAttribute("edit_cust",cust);
return "success";
}
public static String removeRecord(HttpServletRequest request, HttpServletResponse response)
throws Exception
{
String strId = request.getParameter("id");
GenericDelegator delegator = GenericDelegator.getGenericDelegator("default");
GenericValue cust = delegator.findByPrimaryKey("StudyCustomer",UtilMisc.toMap("customerId",strId));
cust.remove();
return "success";
}
}
>=================================================================
程序中的处理大部分可以看懂的,其中有个功能,是
Map paras = UtilMisc.getParameterMap(request);
这是 Ofbiz 的一个有趣但非常有用的功能,它是把 request 中各段的名字和值映射到一个 Map
对象中,然后使用
cust.setNonPKFields(paras);
就可以赋给 Object cust 的各个段,免了我们使用 request.getParameter("name")来取各个
值,在值很多的时候这个功能可以大大减少冗余代码量。
基本程序的逻辑是这样的,
1.从 request 读取传来的值
2.使用 delegator 来处理,Add/Update/Delete/Query
3.将返回结果放到 Session 中传给 JSP
我做了个 Ant build.xml 文件可以帮助编译,把这个文件放在:
c:\ofbiz\ofbiz\testOfbiz\ 目录下,然后在命令行窗口下进入该目录,敲入 ant
来编译(需要保证已经安装 Ant),编译后的 .class 会放在
c:\ofbiz\ofbiz\testOfbiz\com\geeyo\ofbiz 下,
拷贝 c:\ofbiz\ofbiz\testofbiz\com 目录到 c:\ofbiz\ofbiz\partymgr\webapp\WEB-INF\classes
目录下。
build.xml
>=============================================================================
<project name="TestOfbiz" default="dist" basedir=".">
<description>
Test ofbiz
</description>
<!--test cvs-->
<!-- set global properties for this build -->
<property name="src" location="."/>
<property name="build" location="."/>
<property name="lib_dir" location="c:/ofbiz/catalina/shared/lib"/>
<property name="lib1_dir" location="c:/ofbiz/catalina/common/lib"/>
<path id="project.class.path">
<fileset dir="${lib_dir}">
<include name="*.jar"/>
</fileset>
<fileset dir="${lib1_dir}">
<include name="*.jar"/>
</fileset>
</path>
<target name="init">
<!-- Create the time stamp -->
<tstamp/>
<!-- Create the build directory structure used by compile -->
<mkdir dir="${build}"/>
</target>
<target name="compile" depends="init"
description="compile the source " >
<!-- Compile the java code from ${src} into ${build} -->
<javac srcdir="${src}" destdir="${build}">
<classpath refid="project.class.path"/>
</javac>
</target>
<target name="dist" depends="compile"
description="generate the distribution" >
<!-- Create the distribution directory -->
</target>
<target name="clean"
description="clean up" >
<!-- Delete the ${build} and ${dist} directory trees -->
</target>
</project>
>=============================================================================
然后我们来创建 JSP 程序,JSP 程序全部放在
c:\ofbiz\ofbiz\partymgr\webapp\party 下面
1.listofbiz.jsp
>=============================================================================
<%@ taglib uri="ofbizTags" prefix="ofbiz" %>
<%@ page import="java.util.*, org.ofbiz.core.service.ModelService" %>
<%@ page import="org.ofbiz.core.util.*, org.ofbiz.core.pseudotag.*" %>
<%@ page import="org.ofbiz.core.entity.*" %>
<jsp:useBean id="security" type="org.ofbiz.core.security.Security" scope="request" />
<jsp:useBean id="delegator" type="org.ofbiz.core.entity.GenericDelegator" scope="request" />
<script language="JavaScript">
function confirmDelete()
{
return confirm("Are your sure to delete?");
}
</script>
<%if(security.hasEntityPermission("PARTYMGR", "_VIEW", session)) {%>
<table width="600" align="center">
<ofbiz:if name="search_results">
<tr><th>Id</th><th>Name</th><th>Note</th><th></th></tr>
<ofbiz:iterator name="cust" property="search_results">
<tr>
<td><ofbiz:entityfield attribute="cust" field="customerId"/></td>
<td><ofbiz:entityfield attribute="cust" field="customerName"/></td>
<td><ofbiz:entityfield attribute="cust" field="customerNote"/></td>
<td>
<a href='<ofbiz:url>/showtest?customerId=<ofbiz:entityfield attribute="cust" field="customerId"/></ofbiz:url>' class="buttontext">[Edit]</a>
<a href='<ofbiz:url>/removetest?customerId=<ofbiz:entityfield attribute="cust" field="customerId"/></ofbiz:url>' class="buttontext" onclick="return confirmDelete()">[Remove]</a>
</td>
</tr>
</ofbiz:iterator>
</ofbiz:if>
</table>
<table width="200" align="center">
<tr>
<td><a href='<ofbiz:url>/createTestForm</ofbiz:url>'>Create customer</a></td>
</tr>
</table>
<%}else{%>
<h3>You do not have permission to view this page. ("PARTYMGR_VIEW" or "PARTYMGR_ADMIN" needed)</h3>
<%}%>
>=============================================================================
上面程序中需要说明的是
<ofbiz:if name="search_results">
和
<ofbiz:iterator name="cust" property="search_results">,
<ofbiz:if name="search_results"> 是用来检验在 session 或 pageContext 对象
中是否包含 search_results 对象,该对象是由我们的程序放到 session 中的。
<ofbiz:iterator name="cust" property="search_results"> 是用来循环读取对象
search_results(是个 Collection 对象)中存储的各对象,并赋给cust,然后在循环体
中,我们就可以用 cust 对象来读取各个段的值了。
2.createofbiz.jsp
>=============================================================================
<%@ taglib uri="ofbizTags" prefix="ofbiz" %>
<%@ page import="java.util.*, org.ofbiz.core.service.ModelService" %>
<%@ page import="org.ofbiz.core.util.*, org.ofbiz.core.pseudotag.*" %>
<%@ page import="org.ofbiz.core.entity.*" %>
<jsp:useBean id="security" type="org.ofbiz.core.security.Security" scope="request" />
<jsp:useBean id="delegator" type="org.ofbiz.core.entity.GenericDelegator" scope="request" />
<%if(security.hasEntityPermission("PARTYMGR", "_VIEW", session)) {%>
<form method="post" action="<ofbiz:url>/createTest</ofbiz:url>" name="createofbiz">
<table width="300" align="center">
<tr>
<td>Id</td><td><input type="text" name="customerId" size="20"></td>
</tr>
<tr>
<td>Name</td><td><input type="text" name="customerName" size="20"></td>
</tr>
<tr>
<td>Note</td><td><input type="text" name="customerNote" size="30"></td>
</tr>
<tr>
<td></td>
<td><input type="submit"></td>
</tr>
</table>
</form>
<%}else{%>
<h3>You do not have permission to view this page. ("PARTYMGR_VIEW" or "PARTYMGR_ADMIN" needed)</h3>
<%}%>
>=============================================================================
这个程序很容易理解,需要注意的是每个文本框的名字,要跟 Schema StudyCustomer 的各
个段一致,以使程序中跟容易处理。
3.showofbiz.jsp
>=============================================================================
<%@ taglib uri="ofbizTags" prefix="ofbiz" %>
<%@ page import="java.util.*, org.ofbiz.core.service.ModelService" %>
<%@ page import="org.ofbiz.core.util.*, org.ofbiz.core.pseudotag.*" %>
<%@ page import="org.ofbiz.core.entity.*" %>
<jsp:useBean id="security" type="org.ofbiz.core.security.Security" scope="request" />
<jsp:useBean id="delegator" type="org.ofbiz.core.entity.GenericDelegator" scope="request" />
<%if(security.hasEntityPermission("PARTYMGR", "_VIEW", session)) {%>
<form method="post" action="<ofbiz:url>/updateTest</ofbiz:url>" name="updateofbiz">
<table width="300" align="center">
<tr>
<td>Id</td><td><input type="text" name="customerId" size="20" value="<ofbiz:entityfield attribute="edit_cust" field="customerId"/>"></td>
</tr>
<tr>
<td>Name</td><td><input type="text" name="customerName" size="20" value="<ofbiz:entityfield attribute="edit_cust" field="customerName"/>"></td>
</tr>
<tr>
<td>Note</td><td><input type="text" name="customerNote" size="30" value="<ofbiz:entityfield attribute="edit_cust" field="customerNote"/>"></td>
</tr>
<tr>
<td></td>
<td><input type="submit"></td>
</tr>
</table>
</form>
<%}else{%>
<h3>You do not have permission to view this page. ("PARTYMGR_VIEW" or "PARTYMGR_ADMIN" needed)</h3>
<%}%>
>=============================================================================
这个程序中,主要是通过
<ofbiz:entityfield attribute="edit_cust" field="customerId"/>
把取到的对象的段显示出来, 对象 edit_cust 是我们在程序中取到并放到 session 中的。
下面我们来配置 controller.xml 和 regions.xml, 在 controller.xml 中加入:
>=============================================================================
<request-map uri="createTestForm">
<description>Show the create form</description>
<security https="false" auth="false"/>
<response name="success" type="view" value="createTestForm"/>
</request-map>
<request-map uri="testofbiz">
<description>Test Ofbiz</description>
<security https="false" auth="false"/>
<response name="success" type="view" value="testofbiz"/>
</request-map>
<request-map uri="listtest">
<description>List all records</description>
<security https="false" auth="false"/>
<event type="java" path="com.geeyo.ofbiz.TestOfbiz" invoke="lookAllRecords" />
<response name="success" type="view" value="listAllTest"/>
</request-map>
<request-map uri="showtest">
<description>Show records</description>
<security https="false" auth="false"/>
<event type="java" path="com.geeyo.ofbiz.TestOfbiz" invoke="findRecord" />
<response name="success" type="view" value="showTest"/>
</request-map>
<request-map uri="createTest">
<security https="true" auth="true"/>
<event type="java" path="com.geeyo.ofbiz.TestOfbiz" invoke="createNewRecord"/>
<response name="success" type="request" value="listtest"/>
<response name="error" type="view" value="createTestForm"/>
</request-map>
<request-map uri="updateTest">
<description>update a record</description>
<security https="false" auth="false"/>
<event type="java" path="com.geeyo.ofbiz.TestOfbiz" invoke="updateRecord" />
<response name="success" type="request" value="listtest"/>
</request-map>
<request-map uri="removetest">
<description>remove a record</description>
<security https="false" auth="false"/>
<event type="java" path="com.geeyo.ofbiz.TestOfbiz" invoke="removeRecord" />
<response name="success" type="request" value="listtest"/>
</request-map>
<view-map name="listAllTest" type="region"/>
<view-map name="createTestForm" type="region"/>
<view-map name="showTest" type="region"/>
>=============================================================================
在 regions.xml 中加入:
>=============================================================================
<define id='createTestForm' region='MAIN_REGION'>
<put section='title'>Create Ofbiz</put>
<put section='content' content='/party/createofbiz.jsp'/>
</define>
<define id='listAllTest' region='MAIN_REGION'>
<put section='title'>List Ofbiz</put>
<put section='content' content='/party/listofbiz.jsp'/>
</define>
<define id='showTest' region='MAIN_REGION'>
<put section='title'>Show Ofbiz</put>
<put section='content' content='/party/showofbiz.jsp'/>
</define>
>=============================================================================
现在就完成了,我们重新启动 Ofbiz,然后用 IE 访问:
http://localhost:8080/partymgr/control/listtest,用admin/ofbiz 登录后就可以
看到我们刚才的工作成果了,你现在可以增加/删除/修改记录。 |
|