Java-rmi-database-application
Java RMI-データベースアプリケーション
前の章では、クライアントがGUIウィンドウ(JavaFX)を表示するメソッドを呼び出すサンプルRMIアプリケーションを作成しました。
この章では、クライアントプログラムがサーバー上にあるMySQLデータベースのテーブルのレコードを取得する方法を確認する例を取り上げます。
以下に示すように、データベース details に student_data という名前のテーブルがあると仮定します。
+----+--------+--------+------------+---------------------+
| ID | NAME | BRANCH | PERCENTAGE | EMAIL |
+----+--------+--------+------------+---------------------+
| 1 | Ram | IT | 85 | [email protected] |
| 2 | Rahim | EEE | 95 | [email protected] |
| 3 | Robert | ECE | 90 | [email protected] |
+----+--------+--------+------------+---------------------+
ユーザーの名前が myuser で、パスワードが password であると仮定します。
学生クラスの作成
以下に示すように、 setter および getter メソッドで Student クラスを作成します。
public class Student implements java.io.Serializable {
private int id, percent;
private String name, branch, email;
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getBranch() {
return branch;
}
public int getPercent() {
return percent;
}
public String getEmail() {
return email;
}
public void setID(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setBranch(String branch) {
this.branch = branch;
}
public void setPercent(int percent) {
this.percent = percent;
}
public void setEmail(String email) {
this.email = email;
}
}
リモートインターフェイスの定義
リモートインターフェイスを定義します。 ここでは、* getStudents()という名前のメソッドを含む *Hello という名前のリモートインターフェイスを定義しています。 このメソッドは、クラス Student のオブジェクトを含むリストを返します。
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.*;
//Creating Remote interface for our application
public interface Hello extends Remote {
public List<Student> getStudents() throws Exception;
}
実装クラスの開発
クラスを作成し、上記で作成した* interface。*を実装します
ここでは、 Remote interface の* getStudents()メソッドを実装しています。 このメソッドを呼び出すと、 *student_data という名前のテーブルのレコードが取得されます。 setterメソッドを使用してこれらの値をStudentクラスに設定し、リストオブジェクトに追加して、そのリストを返します。
import java.sql.*;
import java.util.*;
//Implementing the remote interface
public class ImplExample implements Hello {
//Implementing the interface method
public List<Student> getStudents() throws Exception {
List<Student> list = new ArrayList<Student>();
//JDBC driver name and database URL
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost:3306/details";
//Database credentials
String USER = "myuser";
String PASS = "password";
Connection conn = null;
Statement stmt = null;
//Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT * FROM student_data";
ResultSet rs = stmt.executeQuery(sql);
//Extract data from result set
while(rs.next()) {
//Retrieve by column name
int id = rs.getInt("id");
String name = rs.getString("name");
String branch = rs.getString("branch");
int percent = rs.getInt("percentage");
String email = rs.getString("email");
//Setting the values
Student student = new Student();
student.setID(id);
student.setName(name);
student.setBranch(branch);
student.setPercent(percent);
student.setEmail(email);
list.add(student);
}
rs.close();
return list;
}
}
サーバープログラム
RMIサーバープログラムは、リモートインターフェイスを実装するか、実装クラスを拡張する必要があります。 ここで、リモートオブジェクトを作成し、それを* RMIレジストリ*にバインドする必要があります。
以下は、このアプリケーションのサーバープログラムです。 ここでは、上記で作成したクラスを拡張し、リモートオブジェクトを作成し、バインド名 hello でRMIレジストリに登録します。
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Server extends ImplExample {
public Server() {}
public static void main(String args[]) {
try {
//Instantiating the implementation class
ImplExample obj = new ImplExample();
//Exporting the object of implementation class (
here we are exporting the remote object to the stub)
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
//Binding the remote object (stub) in the registry
Registry registry = LocateRegistry.getRegistry();
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
クライアントプログラム
以下は、このアプリケーションのクライアントプログラムです。 ここでは、リモートオブジェクトを取得し、* getStudents()*という名前のメソッドを呼び出しています。 リストオブジェクトからテーブルのレコードを取得して表示します。
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.*;
public class Client {
private Client() {}
public static void main(String[] args)throws Exception {
try {
//Getting the registry
Registry registry = LocateRegistry.getRegistry(null);
//Looking up the registry for the remote object
Hello stub = (Hello) registry.lookup("Hello");
//Calling the remote method using the obtained object
List<Student> list = (List)stub.getStudents();
for (Student s:list)v {
//System.out.println("bc "+s.getBranch());
System.out.println("ID: " + s.getId());
System.out.println("name: " + s.getName());
System.out.println("branch: " + s.getBranch());
System.out.println("percent: " + s.getPercent());
System.out.println("email: " + s.getEmail());
}
//System.out.println(list);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
サンプルを実行する手順
RMIの例を実行する手順は次のとおりです。
- ステップ1 *-すべてのプログラムを保存したフォルダーを開き、以下に示すようにすべてのJavaファイルをコンパイルします。
Javac *.java
ステップ2 *-次のコマンドを使用して *rmi レジストリを起動します。
start rmiregistry
これにより、以下に示すように、別のウィンドウで rmi レジストリが開始されます。
- ステップ3 *-以下に示すようにサーバークラスファイルを実行します。
Java Server
- ステップ4 *-以下に示すようにクライアントクラスファイルを実行します。
java Client