1.企业IT部里面的开发同学,经常会遇到java这边要调用sap系统那边的rfc函数来获取sap系统的数据,那么首先你得获得sap的连接,你才能调用rfc函数
window下获取sap系统连接方法如下:
首先你得在web项目lib目录中引入sapjco3.jar这个jar包和sapjco3.dll,准备工作做好了,下面就是编写连接代码,与连接oracle,或者sqlserver
数据库类似,代码如下
public class GetSapConn{
static String ABAP_AS_POOLED = "ABAP_PUBLIC_130_SAPJCO_POOL";
private static void createDataFile()
{
Properties properties = new Properties();
properties.setProperty(DestinationDataProvider.JCO_ASHOST, "");//sap服务器地址
properties.setProperty(DestinationDataProvider.JCO_SYSNR, "00");//系统编号,写00就可以了
properties.setProperty(DestinationDataProvider.JCO_CLIENT, "");//集团号,不知道就问你们的sap basis
properties.setProperty(DestinationDataProvider.JCO_USER, "");//帐号
properties.setProperty(DestinationDataProvider.JCO_PASSWD, "");//密码
properties.setProperty(DestinationDataProvider.JCO_LANG, "zh");//语言
String name = ABAP_AS_POOLED;
String suffix = "jcoDestination";
File cfg = new File(name+"."+suffix);
if(!cfg.exists())
{
try
{
FileOutputStream fos = new FileOutputStream(cfg, false);
properties.store(fos, "for tests only !");
fos.close();
}
catch (Exception e)
{
throw new RuntimeException("Unable to create the destination file " + cfg.getName(), e);
}
}
}
public static JCoDestination getJcoConnection() throws JCoException{
createDataFile();
return JCoDestinationManager.getDestination(ABAP_AS_POOLED);
}
}
ok,连接类已编写OK
下面就介绍一下如何调用rfc函数,比方说sap系统方给了你一个"ZF_EKP_037"的rfc函数
JCoDestination jCoDestination = null;// 连接对象
JCoFunction function = null;// 调用rfc函数对象
try {
jCoDestination = jco.getJcoConnection();
function = jCoDestination.getRepository()
.getFunctionTemplate("ZF_EKP_037").getFunction();
if (null == function) {
throw new RuntimeException("get function not found in sap");
} else {
JCoParameterList paramList = function.getImportParameterList();
paramList.setValue("I_LIFNR", "sap系统传入参数,有多个的话就写多行");
//如果传如参数是内表的形式的话就以如下代码传入sap系统
// JCoTable table1 = function.getTableParameterList().getTable("I_EKPO");
// for (int i = 0; i < purchaseNo.size(); i++) {
// table1.setRow(i);
// table1.appendRow();
// table1.setValue("EBELN", purchaseNo.get(i)[0]);
// table1.setValue("EBELP", purchaseNo.get(i)[1]);
// }
function.execute(jCoDestination);//执行调用函数
JCoTable table2 = function.getTableParameterList().getTable(
"T_MSEG");//得到sap返回的参数,你就把他当作c语言的结构体理解就可以了
//有时候sap那边只是返回一个输出参数,sap比方说你这边输入一个物料号,想得到sap那边的物料描述,这是sap方是不会返回一个内表给你的
//而是只是返回一个输出参数给你这时你就要用到下面的方法来得到输出参数
//paramList = function.getExportParameterList();
//paramList.getString("rfc返回字段字段名称");
for(int i = 0; i < table2.getNumRows(); i++){
table2.setRow(i);
//这里获取sap函数传出内表结构的字段
String maktx = table2.getString("MAKTX");//记住这里MAKTX一定是大写的,不然得不到值
//得到了sap数据,然后下面就是你java擅长的部分了,想封装成什么类型的都由你
}
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
jCoDestination = null;
}
到这里就完整的介绍了如何连接sap系统,并成功调用rfc函数。