この章での機能は、ローカルWebサーバーで実行することができないため、Tomcatや他のWASサービスを使用してください。
Tomcatサーバーの設定については、Apache Tomcat項目を参照してください。
画面の作成(トランザクション)では、あらかじめ作成して保存した XMLファイルのデータを取得し、画面に表示する機能を説明しました。ただし、実際のビジネス環境では、さまざまなデータベースからデータを検索し、入力したデータをデータベースに保存するなどの複雑な業務処理が必要になります。
nexacro platformアプリは、画面(Form)から入力されたデータをサーバーに送信し、データを受信するために transaction()メソッドを使用します。transaction()メソッドは、入力された変数とDatasetを XML形式に変換してサーバーに転送し、コールバック関数を使用して受信したデータを処理します。
このような過程で、クライアントによって配信した変数とDatasetを処理し、データベース内のデータを処理するためにサーバ側で動作するサービスが必要になります。サーバーに実装されたサービスでは、要求されたデータをさまざまなデータベースから取得して適切な形で加工して、クライアントに配信します。要求に問題が生じたときどのような問題なのかを確認することができるエラーコードとメッセージを返します。
サービスは、JSP、Servlet、ASP、PHPなどのサーバー環境によって、さまざまなプログラミング言語で作成することができます。この章では、簡単なJSPサービスを作成し、どのように動作するか確認します。
サービス
画面で入力されたデータをtransaction()メソッドを使用してサーバーに送信し、サーバーに保存されたデータを再度検索するサービスを実装します。
以下の3つのサービスを説明します。
initdata.jsp: デフォルトデータを作成し、サーバー上のDBに保存します。
search.jsp: DBからデータを取得してDatasetを作成し、クライアントに送信します。
save_list.jsp: サーバーに送信されたデータをサーバー上のDBに保存します。
X-API
配布ファイル
nexacro platform X-APIライブラリは、データ処理のためのサービスの実装時に必要な機能をライブラリの形で実装して提供しています。提供するファイルは、次のとおりです。
nexacro17-xapi-1.0.jar (X-APIライブラリファイル)
commons-logging-1.1.1.jar (http://commons.apache.org/proper/commons-logging/)
docs > api (X-APIマニュアル)
例題では、データ処理のために nexacro platform X-APIを使用しています。X-APIはデータ処理のために必要な機能を実装したライブラリであるだけで、X-APIを必ず使用する必要はありません。
X-APIは動作時にサーバーライセンスファイルによって認証を行うため、ライセンスファイルがない場合、正常に動作しません。ただし、評価目的での利用はlocalhostで利用する場合に限定して許諾されます。localhostで利用する場合は、HttpPlatformRequest/HttpPlatformResponseを使用して実装する必要があります。
インストール
Tomcatをインストールして、X-APIの例題で使用するコンテキストファイルを生成します。Tomcatのインストールおよびコンテキストファイルを生成する方法については、Apache Tomcat項目を参照してください。X-APIはTomcatの/WEB-INF/lib/配下などに配置することもできますが、この例題では別の場所に置いてあるX-APIを参照する内容になります。
1
コンテキストファイルを生成します。下のパスにCustomerList.xmlファイルを生成します。
C:\Program Files\Apache Software Foundation\Tomcat 8.5\conf\Catalina\localhost
$r_title(CustomerList.xml) <Context path="/CustomerList" docBase="E:\88_TEST\02_BUILD\CustomerList" debug="0" prvileged="true" reloadable="true"> <Logger className="org.apache.catalina.logger.FileLogger" directory="logs" prefix="localhost_log." suffix=".txt" timestame="true"/> </Context>
2
ダウンロードしたX-APIファイルを解凍します。解除すると表示される2つ(docs、lib)のフォルダの中でlibフォルダの中にある2つのjarファイルを使用します。
3
docBaseに指定されたフォルダを作成し、該当フォルダの中にWEB-INFフォルダを生成します。そして、WEB-INFフォルダの中にlibフォルダを生成して、jarファイルとライセンスファイルをコピーします。
E:\88_TEST\02_BUILD\CustomerList\WEB-INF\lib
4
docBaseに指定したフォルダの下に、テストのためのjspファイルを生成します。
E:\88_TEST\02_BUILD\CustomerList
$r_title(test.jsp) <%@ page contentType="text/html; charset=UTF-8" %> <html> <head> <title>JarInfo</title> <style> * { font-family: Verdana } </style> </head> <body> <pre> <% new com.nexacro17.xapi.util.JarInfo().info(out); %> </pre> </body> </html>
5
Webブラウザから下記のアドレスにアクセスしたときに、インストール情報が正常に表示されるのを確認します。インストール情報が表示されるのは、正常にX-APIがインストールされたのを意味します。
http://localhost:8080/CustomerList/test.jsp
WEB-INFはWeb Informationの略です。コンテキストルートディレクトリ内にありますが、ユーザーがアクセスすることができず、内部的に参照するための情報を含んでいます。
libディレクトリには、jarファイルを入れておくことができる空間です。jarはJava Archiveの略として、複数のJavaクラスファイルとリソースなどを一つのファイルにまとめてライブラリのように管理するファイルです。
ライブラリをコピーする場所は、使用しているWASの設定によって異なる場合があります。
ライブラリファイルをコピーした後は、WASサービスを再起動してください。
WASの設定によっては、再起動が必要ない場合もあります。
ライブラリファイルとライセンスファイルは、同じ場所にコピーしなければ認識することができません。
本例題ではSQLiteを使用しています。必要なファイルは下記のURLよりダウンロードしてください。
・JDBCドライバー(※本例題ではsqlite-jdbc-3.8.11.2.jarを使用しています)
https://bitbucket.org/xerial/sqlite-jdbc/downloads/
・例題用のsqlite3ファイル(データは0件の状態です。JSPと同じ場所に配置します。)
http://dev01.nexaweb.co.jp/~nexacro/nexacro17_tutorial_db.zip
専用オブジェクト
接続されたライブラリで使用される専用オブジェクトは次のようです。
PlatformData : データを保存するデフォルトオブジェクト
HttpPlatformRequest : JSP要求時にXML Format Dataをロードしてオブジェクト化するInputオブジェクト
HttpPlatformResponse : JSP要求時にXML Format Dataを出力するOutputオブジェクト
DatasetList & Dataset : データを2次元Table形式またはTable Arrayタイプで保存
VariableList & Variable : I/O引数値として使用される値を保存
詳しくは、ライブラリに含まれた X-APIマニュアルを参照してください。
画面にButtonコンポーネントを追加
既存の画面にデータの初期化と保存のためのButtonコンポーネントを追加します。
コンポーネント | プロパティ | 値 | 説明 |
---|---|---|---|
1 Button | id | btnSaveList | |
text | Save | ボタンに表示する文字列 | |
2 Button | id | btnInitdata | |
text | Initdata | ボタンに表示する文字列 |
initdata.jsp
初期データを作成し、サーバー上のDBに保存します。
コードの実装
Javaライブラリ指定
JSPサービスを作成するために、デフォルトJavaライブラリを指定します。コードは次のとおりです。
<!-- 1. library import --> <%@ page import="org.apache.commons.logging.*" %> <%@ page import="java.io.*" %> <%@ page import="java.util.*" %> <%@ page import="java.sql.*" %> <%@ page import="com.nexacro17.xapi.data.*" %> <%@ page import="com.nexacro17.xapi.tx.*" %>
MIMEタイプ定義
XML生成のための MIME(Multipurpose Internet Mail Extensions)タイプを定義します。
<!-- 2. Defining a MIME type --> <%@ page contentType="text/xml; charset=UTF-8" %>
デフォルトオブジェクト(PlatformData)の生成
データを処理するためのデフォルトオブジェクトを宣言します。デフォルトオブジェクトである PlatformDataはnexacro platformアプリケーションで使用されるすべてのデータ(Dataset、変数)をまとめて格納することができるオブジェクトです。
PlatformDataを宣言するコードは次のとおりです。
/** 3. nexacro platform Basic Object creation **/ PlatformData pdata = new PlatformData();
ErrorCode、ErrorMsg処理
例外が発生したときに処理するための部分です。
/** 4. ErrorCode, ErrorMsg creation **/ int nErrorCode = 0; String strErrorMsg = "START"; try { : /** 5.2 set the ErrorCode and ErrorMsg about success**/ nErrorCode = 0; strErrorMsg = "SUCC"; /** 5.3 set the ErrorCode and ErrorMsg about fail **/ }catch(SQLException e){ nErrorCode = -1; strErrorMsg = e.getMessage(); } : }catch(Throwable th){ nErrorCode = -2; strErrorMsg = th.getMessage(); } /** 5.4 Saving ErrorCode and ErrorMsg to send them to the client **/ VariableList out_varList = pdata.getVariableList(); out_varList.add("ErrorCode", nErrorCode); out_varList.add("ErrorMsg", strErrorMsg);
結果データをクライアントに送る
処理結果を返すために、PlatformDataオブジェクトを使用します。この時、ErrorCodeとErrorMsgが一緒に送信されます。
VariableListは PlatformDataのメンバーなので、実行した結果値はPlatformDataオブジェクトに含まれています。ここで、PlatformDataのデータをnexacro platformで処理することができるXML Formatで抽出して送信する部分を実装してみましょう。データを転送する機能を簡単に実装するためにHttpPlatformResponseオブジェクトを作成し、PlatformDataオブジェクトからデータを出力するコードは次のとおりです。
/** 6. Sending result data to the client **/ HttpPlatformResponse pRes = new HttpPlatformResponse(response, request); pRes.setContentType(PlatformType.CONTENT_TYPE_XML) ; pRes.setCharset("utf-8") ; pRes.setData(pdata); pRes.pdata();
正常にデータが処理されている場合、クライアントに送信される XML値は以下のとおりです。
<Root xmlns="http://www.nexacroplatform.com/platform/dataset"> <Parameters> <Parameter id="ErrorCode" type="int">0</Parameter> <Parameter id="ErrorMsg" type="string">SUCC</Parameter> </Parameters> </Root>
全体コード
<!-- 1. library import --> <%@ page import="org.apache.commons.logging.*" %> <%@ page import="java.io.*" %> <%@ page import="java.util.*" %> <%@ page import="java.sql.*" %> <%@ page import="com.nexacro17.xapi.data.*" %> <%@ page import="com.nexacro17.xapi.tx.*" %> <!-- 2. Defining a MIME type --> <%@ page contentType="text/xml; charset=UTF-8" %> <% HttpPlatformRequest pReq = new HttpPlatformRequest(request); pReq.receiveData(); /** 3. nexacro platform Basic Object creation **/ PlatformData pdata = new PlatformData(); /** 4. ErrorCode, ErrorMsg creation **/ int nErrorCode = 0; String strErrorMsg = "START"; /** 5. handle data : save data to DB **/ try { /** 5.1 save data to DB **/ /******* JDBC Connection ********/ Connection conn = null; Statement stmt = null; try{ Class.forName("org.sqlite.JDBC"); String contextRealPath = request.getSession().getServletContext().getRealPath("/"); String path = contextRealPath + "/tutorial.sqlite3"; conn = DriverManager.getConnection("jdbc:sqlite:" + path); stmt = conn.createStatement(); String SQL = ""; /******* INSERT *******/ SQL = "INSERT OR IGNORE INTO CUSTOMERS(id, \n" + " name, \n" + " email, \n" + " phone, \n" + " comp_name, \n" + " department, \n" + " comp_phone, \n" + " comp_addr) \n" + "VALUES('TC-001', \n" + " 'Tzuyu', \n" + " 'ceo@twice.com', \n" + " '6987-6543', \n" + " 'TWICE', \n" + " '0', \n" + " '6506-7000', \n" + " 'Tokyo') "; System.out.println(">>>insert : " + SQL); stmt.executeUpdate(SQL); /** 5.2 set the ErrorCode and ErrorMsg about success**/ nErrorCode = 0; strErrorMsg = "SUCC"; /** 5.3 set the ErrorCode and ErrorMsg about fail **/ }catch(SQLException e){ nErrorCode = -1; strErrorMsg = e.getMessage(); } /********* JDBC Close *********/ if( stmt != null){ try{ stmt.close(); }catch(Exception e){ nErrorCode = -1; strErrorMsg = e.getMessage(); } } if( conn != null){ try{ conn.close(); }catch(Exception e){ nErrorCode = -1; strErrorMsg = e.getMessage(); } } }catch(Throwable th){ nErrorCode = -2; strErrorMsg = th.getMessage(); } /** 5.4 Saving ErrorCode and ErrorMsg to send them to the client **/ VariableList out_varList = pdata.getVariableList(); out_varList.add("ErrorCode", nErrorCode); out_varList.add("ErrorMsg", strErrorMsg); /** 6. Sending result data to the client **/ HttpPlatformResponse pRes = new HttpPlatformResponse(response, request); pRes.setContentType(PlatformType.CONTENT_TYPE_XML) ; pRes.setCharset("utf-8") ; pRes.setData(pdata); pRes.sendData(); %>
データ初期化イベント
ここでは前章で作成したJSPをリクエストURLとして指定してトランザクションを行うスクリプトを作成します。フルパスのURLを指定することができますが、毎回フルパスのURLを指定せずに、TypeDefinitionにサービスとして URLを登録しておくことで、URLが変更になった場合における変更が容易になります。
登録したサービスはの参照方法は下記の通りです。
var url = "[Service ID]::[file name]";
この例題ではURL指定時にPrefixIDを使用します。サービス登録はProject ExplorerのType Definition>Servicesをダブルクリックすると表示される画面から行います。
画面にButtonコンポーネントを追加にて追加した➋Initdataボタンに対して、次のように onclickイベントを追加します。ボタンをクリックすると、initdata.jspサービスが呼び出され、サーバー上のDBにデータを生成します。
this.divCommand_btnInitdata_onclick = function(obj:nexacro.Button, e:nexacro.ClickEventInfo) { var id = "initdata"; var url = "SvcList::initdata.jsp"; var reqDs = ""; var respDs = ""; var args = ""; var callback = "initdata_received"; this.transaction(id, url, reqDs, respDs, args, callback); } this.initdata_received = function(id, code, message) { if (code == 0) { this.alert(message); trace(message); } else { this.alert("Error["+code+"]:"+message); trace("Error["+code+"]:"+message); } }
search.jsp
保存されたファイルからデータをロードしてDatasetを作成し、クライアントに送信します。
コードの実装
Javaライブラリ指定
JSPサービスを作成するために、デフォルトJavaライブラリを指定します。コードは次のとおりです。
<!-- 1. library import --> <%@ page import="org.apache.commons.logging.*" %> <%@ page import="java.io.*" %> <%@ page import="java.util.*" %> <%@ page import="java.sql.*" %> <%@ page import="com.nexacro17.xapi.data.*" %> <%@ page import="com.nexacro17.xapi.tx.*" %>
MIMEタイプ定義
XML生成のための MIME(Multipurpose Internet Mail Extensions)タイプを定義します。
<!-- 2. Defining a MIME type --> <%@ page contentType="text/xml; charset=UTF-8" %>
デフォルトオブジェクト(PlatformData)生成
データを処理するためのデフォルトオブジェクトを宣言します。デフォルトオブジェクトである PlatformDataはnexacro platformアプリケーションで使用されるすべてのデータ(Dataset、変数)をまとめて格納することができるオブジェクトです。
PlatformDataを宣言するコードは次のとおりです。
/** 3. nexacro platform Basic Object creation **/ PlatformData pdata = new PlatformData();
DBからデータを取得し、Datasetを生成
CUSTOMERSテーブルのデータを取得し、PlatformDataオブジェクトに保存します。PlatformDataオブジェクトにDatasetが含まれています。
CUSTOMERSテーブルののデータを取得し、PlatformDataに格納するコードは次のとおりです。
下記の例題でのDB接続およびSQL発行などDBからデータを取得するコードは、使用する環境に合わせて実装してください。
/** 5. handle data : get the data from DB and save to Dastaset **/ try { /** 5.1 get the data from DB **/ /******* JDBC Connection ********/ Connection conn = null; Statement stmt = null; ResultSet rs = null; try{ Class.forName("org.sqlite.JDBC"); String contextRealPath = request.getSession().getServletContext().getRealPath("/"); String path = contextRealPath + "/tutorial.sqlite3"; conn = DriverManager.getConnection("jdbc:sqlite:" + path); stmt = conn.createStatement(); /******* SQL *******/ String SQL; SQL = "SELECT * FROM CUSTOMERS"; rs= stmt.executeQuery(SQL); /** 5.2 Save the data to Dataset **/ DataSet ds = new DataSet("customers"); ds.addColumn("id" , DataTypes.STRING, (short)10 ); ds.addColumn("name" , DataTypes.STRING, (short)16 ); ds.addColumn("email" , DataTypes.STRING, (short)32 ); ds.addColumn("phone" , DataTypes.STRING, (short)16 ); ds.addColumn("comp_name" , DataTypes.STRING, (short)32 ); ds.addColumn("department" , DataTypes.STRING, (short)32 ); ds.addColumn("comp_phone" , DataTypes.STRING, (short)16 ); ds.addColumn("comp_addr" , DataTypes.STRING, (short)256 ); while(rs.next()){ int row = ds.newRow(); ds.set(row, "id" , rs.getString("id") ); ds.set(row, "name" , rs.getString("name") ); ds.set(row, "email" , rs.getString("email") ); ds.set(row, "phone" , rs.getString("phone") ); ds.set(row, "comp_name" , rs.getString("comp_name") ); ds.set(row, "department" , rs.getString("department")); ds.set(row, "comp_phone" , rs.getString("comp_phone")); ds.set(row, "comp_addr" , rs.getString("comp_addr") ); : } pdata.addDataSet(ds); :
ErrorCode、ErrorMsg処理
例外が発生したときに処理するための部分です。
/** 4. ErrorCode, ErrorMsg creation **/ int nErrorCode = 0; String strErrorMsg = "START"; try { : /** 5.3 set the ErrorCode and ErrorMsg about success**/ nErrorCode = 0; strErrorMsg = "SUCC"; /** 5.4 set the ErrorCode and ErrorMsg about fail **/ }catch(SQLException e){ nErrorCode = -1; strErrorMsg = e.getMessage(); } : }catch(Throwable th){ nErrorCode = -2; strErrorMsg = th.getMessage(); } /** 5.5 Saving ErrorCode and ErrorMsg to send them to the client **/ VariableList out_varList = pdata.getVariableList(); out_varList.add("ErrorCode", nErrorCode); out_varList.add("ErrorMsg", strErrorMsg);
結果データをクライアントに送る
処理結果を返すために、PlatformDataオブジェクトを使用します。この時、ErrorCodeとErrorMsgが一緒に送信されます。
initdata.jspでのPlatformDataオブジェクトはErrorCodeとErrorMsgのみ持っていますが、search.jspではPlatformDataにクライアントに返す名刺リストのDatasetが含まれています。
VariableListは PlatformDataのメンバーなので、実行した結果値はPlatformDataオブジェクトに含まれています。ここで、PlatformDataのデータをnexacro platformで処理することができるXML Formatで抽出して送信する部分を実装してみましょう。データを転送する機能を簡単に実装するためにHttpPlatformResponseオブジェクトを作成し、PlatformDataオブジェクトからデータを出力するコードは次のとおりです。
/** 6. Sending result data to the client **/ HttpPlatformResponse pRes = new HttpPlatformResponse(response, request); pRes.setContentType(PlatformType.CONTENT_TYPE_XML) ; pRes.setCharset("utf-8") ; pRes.setData(pdata); pRes.sendData();
正常にデータが処理されている場合、クライアントに送信される XML値は以下のとおりです。
<Root xmlns="http://www.nexacroplatform.com/platform/dataset"> <Parameters> <Parameter id="ErrorCode" type="int">0</Parameter> <Parameter id="ErrorMsg" type="string">SUCC</Parameter> </Parameters> <Dataset id="customers"> <ColumnInfo> <Column id="id" type="string" size="10"/> <Column id="name" type="string" size="16"/> <Column id="email" type="string" size="32"/> <Column id="phone" type="string" size="16"/> <Column id="comp_name" type="string" size="32"/> <Column id="department" type="string" size="32"/> <Column id="comp_phone" type="string" size="16"/> <Column id="comp_addr" type="string" size="256"/> </ColumnInfo> <Rows> <Row> <Col id="id">TC-001</Col> <Col id="name">Tzuyu</Col> <Col id="email">ceo@twice.com</Col> <Col id="phone">6987-6543</Col> <Col id="comp_name">TWICE</Col> <Col id="department">0</Col> <Col id="comp_phone">6506-7000</Col> <Col id="comp_addr">Tokyo</Col> </Row> </Rows> </Dataset> </Root>
全体コード
<!-- 1. library import --> <%@ page import="org.apache.commons.logging.*" %> <%@ page import="java.io.*" %> <%@ page import="java.util.*" %> <%@ page import="java.sql.*" %> <%@ page import="com.nexacro17.xapi.data.*" %> <%@ page import="com.nexacro17.xapi.tx.*" %> <!-- 2. Defining a MIME type --> <%@ page contentType="text/xml; charset=UTF-8" %> <% HttpPlatformRequest pReq = new HttpPlatformRequest(request); pReq.receiveData(); /** 3. nexacro platform Basic Object creation **/ PlatformData pdata = new PlatformData(); /** 4. ErrorCode, ErrorMsg creation **/ int nErrorCode = 0; String strErrorMsg = "START"; /** 5. handle data : get the data from DB and save to Dastaset **/ try { /** 5.1 get the data from DB **/ /******* JDBC Connection ********/ Connection conn = null; Statement stmt = null; ResultSet rs = null; try{ Class.forName("org.sqlite.JDBC"); String contextRealPath = request.getSession().getServletContext().getRealPath("/"); String path = contextRealPath + "/tutorial.sqlite3"; conn = DriverManager.getConnection("jdbc:sqlite:" + path); stmt = conn.createStatement(); /******* SQL *******/ String SQL; SQL = "SELECT * FROM CUSTOMERS"; rs= stmt.executeQuery(SQL); /** 5.2 Save the data to Dataset **/ DataSet ds = new DataSet("customers"); ds.addColumn("id" , DataTypes.STRING, (short)10 ); ds.addColumn("name" , DataTypes.STRING, (short)16 ); ds.addColumn("email" , DataTypes.STRING, (short)32 ); ds.addColumn("phone" , DataTypes.STRING, (short)16 ); ds.addColumn("comp_name" , DataTypes.STRING, (short)32 ); ds.addColumn("department" , DataTypes.STRING, (short)32 ); ds.addColumn("comp_phone" , DataTypes.STRING, (short)16 ); ds.addColumn("comp_addr" , DataTypes.STRING, (short)256 ); while(rs.next()){ int row = ds.newRow(); ds.set(row, "id" , rs.getString("id") ); ds.set(row, "name" , rs.getString("name") ); ds.set(row, "email" , rs.getString("email") ); ds.set(row, "phone" , rs.getString("phone") ); ds.set(row, "comp_name" , rs.getString("comp_name") ); ds.set(row, "department" , rs.getString("department")); ds.set(row, "comp_phone" , rs.getString("comp_phone")); ds.set(row, "comp_addr" , rs.getString("comp_addr") ); System.out.println("No." + row); System.out.println(rs.getString("id") ); System.out.println(rs.getString("name") ); System.out.println(rs.getString("email") ); System.out.println(rs.getString("phone") ); System.out.println(rs.getString("comp_name") ); System.out.println(rs.getString("department") ); System.out.println(rs.getString("comp_phone") ); System.out.println(rs.getString("comp_addr") ); } pdata.addDataSet(ds); /** 5.3 Setting ErrorCode and ErrorMsg for success **/ nErrorCode = 0; strErrorMsg = "SUCC"; /** 5.4 set the ErrorCode and ErrorMsg about fail **/ }catch(SQLException e){ nErrorCode = -1; strErrorMsg = e.getMessage(); } /********* JDBC Close *********/ if( stmt != null){ try{ stmt.close(); }catch(Exception e){ nErrorCode = -1; strErrorMsg = e.getMessage(); } } if( conn != null){ try{ conn.close(); }catch(Exception e){ nErrorCode = -1; strErrorMsg = e.getMessage(); } } }catch(Throwable th){ nErrorCode = -2; strErrorMsg = th.getMessage(); } /** 5.5 Saving ErrorCode and ErrorMsg to send them to the client **/ VariableList out_varList = pdata.getVariableList(); out_varList.add("ErrorCode", nErrorCode); out_varList.add("ErrorMsg", strErrorMsg); /** 6. Sending result data to the client **/ HttpPlatformResponse pRes = new HttpPlatformResponse(response, request); pRes.setContentType(PlatformType.CONTENT_TYPE_XML) ; pRes.setCharset("utf-8") ; pRes.setData(pdata); pRes.sendData(); %>
データ検索イベント
画面の作成(トランザクション)で作成した画面で検索ボタンに指定された onclickイベントを修正します。画面内のボタンをクリックすると search.jspサービスが呼び出されながらサーバーに保存されたファイルをロードしてDatasetを返します。
サーバーから送信されるDatasetの情報は、画面内作成された dsCustomersDatasetに含まれて、該当データをグリッドに表示します。
this.divCommand_btnSearch_onclick = function(obj:nexacro.Button, e:nexacro.ClickEventInfo) { var id = "search"; var url = "SvcList::search.jsp"; var reqDs = ""; var respDs = "dsCustomers=customers"; var args = ""; var callback = "search_received"; this.transaction(id, url, reqDs, respDs, args, callback); } this.search_received = function(id, code, message) { if (code == 0) { var rowcount = this.dsCustomers.rowcount; this.alert(rowcount + " numbers of data have been found."); trace(rowcount + " numbers of data have been found."); } else { this.alert("Error["+code+"]:"+message); trace("Error["+code+"]:"+message); } }
save_list.jsp
サーバーに送信されたデータをサーバー上のDBに保存します。
コードの実装
Javaライブラリ指定
JSPサービスを作成するために、デフォルトJavaライブラリを指定します。コードは次のとおりです。
<!-- 1. library import --> <%@ page import="org.apache.commons.logging.*" %> <%@ page import="java.io.*" %> <%@ page import="java.util.*" %> <%@ page import="java.sql.*" %> <%@ page import="com.nexacro17.xapi.data.*" %> <%@ page import="com.nexacro17.xapi.tx.*" %>
MIMEタイプ定義
XML生成のための MIME(Multipurpose Internet Mail Extensions)タイプを定義します。
<!-- 2. Defining a MIME type --> <%@ page contentType="text/xml; charset=UTF-8" %>
デフォルトオブジェクト(PlatformData)生成
データを処理するためのデフォルトオブジェクトを宣言します。デフォルトオブジェクトである PlatformDataはnexacro platformアプリケーションで使用されるすべてのデータ(Dataset、変数)をまとめて格納することができるオブジェクトです。
PlatformDataを宣言するコードは次のとおりです。
/** 3. nexacro platform Basic Object creation **/ PlatformData pdata = new PlatformData();
クライアントのリクエスト
クライアントからパラメータとして送信されたDatasetを受信して処理します。
/** 5. Receiving a request from the client **/ // create HttpPlatformRequest for receive data from client HttpPlatformRequest req = new HttpPlatformRequest(request); req.receiveData();
受信したたデータを抽出した後、DBに保存する
クライアントが送信した情報を処理できるように変換したPlatformDataからDatasetを抽出します。生成されたPlatformDataはDBに保存します。
下記の例題でのDB接続およびSQL発行などDBを更新するコードは、使用する環境に合わせて実装してください。
/** 6. Processing data: load data and save data to DB **/ /** 6.1 Loading data from the http object **/ pdata = req.getData(); /** Obtaining a dataset from the received data **/ DataSet ds = pdata.getDataSet("customers"); /** 6.2 Saving data to DB **/ try{ /******* JDBC Connection ********/ Connection conn = null; Statement stmt = null; ResultSet rs = null; try{ Class.forName("org.sqlite.JDBC"); String contextRealPath = request.getSession().getServletContext().getRealPath("/"); String path = contextRealPath + "/tutorial.sqlite3"; conn = DriverManager.getConnection("jdbc:sqlite:" + path); stmt = conn.createStatement(); /******* SQL ********/ String SQL = ""; int i; for( i = 0; i < ds.getRowCount(); i++ ){ SQL = "INSERT OR REPLACE INTO CUSTOMERS(id, \n" + " name, \n" + " email, \n" + " phone, \n" + " comp_name, \n" + " department, \n" + " comp_phone, \n" + " comp_addr) \n" + "VALUES('"+ dsGet (ds, i, "id" ) + "', \n" + " '"+ dsGet (ds, i, "name" ) + "', \n" + " '"+ dsGet (ds, i, "email" ) + "', \n" + " '"+ dsGet (ds, i, "phone" ) + "', \n" + " '"+ dsGet (ds, i, "comp_name" ) + "', \n" + " '"+ dsGet (ds, i, "department" ) + "', \n" + " '"+ dsGet (ds, i, "comp_phone" ) + "', \n" + " '"+ dsGet (ds, i, "comp_addr" ) + "')"; System.out.println(">>>insert : " + SQL); } stmt.executeUpdate(SQL); :
ErrorCode、ErrorMsg処理
例外が発生したときに処理するための部分です。正常に処理した場合には、正常に保存されたメッセージを返します。
/** 6.1 ErrorCode, ErrorMsg creation **/ int nErrorCode = 0; String strErrorMsg = "START"; try { : /** 6.3 Setting ErrorCode and ErrorMsg for success **/ nErrorCode = 0; strErrorMsg = "person list saved complete : row count("+ds.getRowCount()+")"; /** 6.4 set the ErrorCode and ErrorMsg about fail **/ }catch(SQLException e){ nErrorCode = -1; strErrorMsg = e.getMessage(); } : }catch(Throwable th){ nErrorCode = -2; strErrorMsg = th.getMessage(); } /** 6.5 Saving ErrorCode and ErrorMsg to send them to the client **/ VariableList out_varList = pdata.getVariableList(); out_varList.add("ErrorCode", nErrorCode); out_varList.add("ErrorMsg", strErrorMsg);
結果データをクライアントに送る
処理結果を返すために、PlatformDataオブジェクトを使用します。この時、ErrorCodeとErrorMsgが一緒に送信されます。
VariableListは PlatformDataのメンバーなので、実行した結果値はPlatformDataオブジェクトに含まれています。ここで、PlatformDataのデータをnexacro platformで処理することができるXML Formatで抽出して送信する部分を実装してみましょう。データを転送する機能を簡単に実装するためにHttpPlatformResponseオブジェクトを作成し、PlatformDataオブジェクトからデータを出力するコードは次のとおりです。
/** 7. Sending result data to the client **/ HttpPlatformResponse res = new HttpPlatformResponse(response, request); res.setContentType(PlatformType.CONTENT_TYPE_XML) ; res.setCharset("utf-8") ; res.setData(pdata); res.sendData();
全体コード
<!-- 1. library import --> <%@ page import="org.apache.commons.logging.*" %> <%@ page import="java.io.*" %> <%@ page import="java.util.*" %> <%@ page import="java.sql.*" %> <%@ page import="com.nexacro17.xapi.data.*" %> <%@ page import="com.nexacro17.xapi.tx.*" %> <!-- 2. Defining a MIME type --> <%@ page contentType="text/xml; charset=UTF-8" %> <%! //Dataset public String dsGet (DataSet ds, int rowno, String colid) throws Exception { String value; value = ds.getString(rowno, colid); if( value == null ){ return ""; }else{ return value; } } %> <% /** 3. nexacro platform Basic Object creation **/ PlatformData pdata = new PlatformData(); /** 4. ErrorCode, ErrorMsg creation **/ int nErrorCode = 0; String strErrorMsg = "START"; /** 5. Receiving a request from the client **/ // create HttpPlatformRequest for receive data from client HttpPlatformRequest req = new HttpPlatformRequest(request); req.receiveData(); /** 6. Processing data: load data and save data to DB **/ /** 6.1 Loading data from the http object **/ pdata = req.getData(); /** Obtaining a dataset from the received data **/ DataSet ds = pdata.getDataSet("customers"); /** 6.2 Saving data to DB **/ try{ /******* JDBC Connection ********/ Connection conn = null; Statement stmt = null; ResultSet rs = null; try{ Class.forName("org.sqlite.JDBC"); String contextRealPath = request.getSession().getServletContext().getRealPath("/"); String path = contextRealPath + "/tutorial.sqlite3"; conn = DriverManager.getConnection("jdbc:sqlite:" + path); stmt = conn.createStatement(); /******* SQL ********/ String SQL = ""; int i; for( i = 0; i < ds.getRowCount(); i++ ){ SQL = "INSERT OR REPLACE INTO CUSTOMERS(id, \n" + " name, \n" + " email, \n" + " phone, \n" + " comp_name, \n" + " department, \n" + " comp_phone, \n" + " comp_addr) \n" + "VALUES('"+ dsGet (ds, i, "id" ) + "', \n" + " '"+ dsGet (ds, i, "name" ) + "', \n" + " '"+ dsGet (ds, i, "email" ) + "', \n" + " '"+ dsGet (ds, i, "phone" ) + "', \n" + " '"+ dsGet (ds, i, "comp_name" ) + "', \n" + " '"+ dsGet (ds, i, "department" ) + "', \n" + " '"+ dsGet (ds, i, "comp_phone" ) + "', \n" + " '"+ dsGet (ds, i, "comp_addr" ) + "')"; System.out.println(">>>insert : " + SQL); } stmt.executeUpdate(SQL); /** 6.3 Setting ErrorCode and ErrorMsg for success **/ nErrorCode = 0; strErrorMsg = "person list saved complete : row count("+ds.getRowCount()+")"; /** 6.4 set the ErrorCode and ErrorMsg about fail **/ }catch(SQLException e){ nErrorCode = -1; strErrorMsg = e.getMessage(); } /********* JDBC Close *********/ if( stmt != null){ try{ stmt.close(); }catch(Exception e){ nErrorCode = -1; strErrorMsg = e.getMessage(); } } if( conn != null){ try{ conn.close(); }catch(Exception e){ nErrorCode = -1; strErrorMsg = e.getMessage(); } } }catch(Throwable th){ nErrorCode = -2; strErrorMsg = th.getMessage(); } /** 6.5 Saving ErrorCode and ErrorMsg to send them to the client **/ VariableList varList = pdata.getVariableList(); varList.add("ErrorCode", nErrorCode); varList.add("ErrorMsg", strErrorMsg); /** 7. Sending result data to the client **/ HttpPlatformResponse res = new HttpPlatformResponse(response, request); res.setContentType(PlatformType.CONTENT_TYPE_XML) ; res.setCharset("utf-8") ; res.setData(pdata); res.sendData(); %>
データ保存イベント
画面の作成(トランザクション)で作成した画面にボタンコンポーネントを追加し、次のように onclickイベントを追加します。画面内のボタンをクリックすると save_list.jspサービスが呼び出されながら画面で修正したDatasetをサーバーに送信して再びファイルに保存します。
データを変更することができる機能を簡単に追加します。画面内のグリッドをダブルクリックして、Grid Contents Editorを実行した後、Name項目を選択して edittypeプロパティを「text」に変更します。データ検索後、該当項目をダブルクリックすると、データを変更することができます。
修正したデータを保存した後、画面を更新し検索ボタンをクリックすると、変更されたデータが検索されることを確認することができます。
this.divCommand_btnSaveList_onclick = function(obj:nexacro.Button, e:nexacro.ClickEventInfo) { var id = "save_list"; var url = "SvcList::save_list.jsp"; var reqDs = "customers=dsCustomers"; var respDs = ""; var args = ""; var callback = "save_list_received"; this.transaction(id, url, reqDs, respDs, args, callback); } this.save_list_received = function(id, code, message) { if (code == 0) { this.alert(message); trace(message); } else { this.alert("Error["+code+"]:"+message); trace("Error["+code+"]:"+message); } }