在上一章中,我们创建了一个示例RMI应用程序,其中客户端调用一个显示GUI窗口(JavaFX)的方法。
在本章中,我们将以一个示例为例,说明客户端程序如何在服务器上的MySQL数据库中检索表的记录。
假设我们在数据库详细信息中有一个名为student_data的表,如下所示。
+----+--------+--------+------------+---------------------+
| ID | NAME | BRANCH | PERCENTAGE | EMAIL |
+----+--------+--------+------------+---------------------+
| 1 | Ram | IT | 85 | ram123@gmail.com |
| 2 | Rahim | EEE | 95 | rahim123@gmail.com |
| 3 | Robert | ECE | 90 | robert123@gmail.com |
+----+--------+--------+------------+---------------------+
假设用户名是myuser,密码是password。
创建学生班
如下所示,使用setter和getter方法创建一个Student类。
publicclassStudentimplementsjava.io.Serializable{privateintid,percent;privateStringname,branch,email;publicintgetId(){returnid;}publicStringgetName(){returnname;}publicStringgetBranch(){returnbranch;}publicintgetPercent(){returnpercent;}publicStringgetEmail(){returnemail;}publicvoidsetID(intid){this.id=id;}publicvoidsetName(Stringname){this.name=name;}publicvoidsetBranch(Stringbranch){this.branch=branch;}publicvoidsetPercent(intpercent){this.percent=percent;}publicvoidsetEmail(Stringemail){this.email=email;}}
定义远程接口
定义远程接口。在这里,我们定义了一个名为Hello的远程接口,其中包含一个名为getStudents()的方法。此方法返回一个列表,其中包含Student类的对象。
importjava.rmi.Remote;importjava.rmi.RemoteException;importjava.util.*;// Creating Remote interface for our applicationpublicinterfaceHelloextendsRemote{publicListgetStudents()throwsException;}
开发实施类
创建一个类并实现上面创建的接口。
在这里,我们实现了Remote接口的getStudents()方法。调用此方法时,它将检索名为student_data的表的记录。使用其setter方法将这些值设置为Student类,将其添加到列表对象并返回该列表。
importjava.sql.*;importjava.util.*;// Implementing the remote interfacepublicclassImplExampleimplementsHello{// Implementing the interface methodpublicListgetStudents()throwsException{Listlist=newArrayList();// JDBC driver name and database URLStringJDBC_DRIVER="com.mysql.jdbc.Driver";StringDB_URL="jdbc:mysql://localhost:3306/details";// Database credentialsStringUSER="myuser";StringPASS="password";Connectionconn=null;Statementstmt=null;//Register JDBC driverClass.forName("com.mysql.jdbc.Driver");//Open a connectionSystem.out.println("Connecting to a selected database...");conn=DriverManager.getConnection(DB_URL,USER,PASS);System.out.println("Connected database successfully...");//Execute a querySystem.out.println("Creating statement...");stmt=conn.createStatement();Stringsql="SELECT * FROM student_data";ResultSetrs=stmt.executeQuery(sql);//Extract data from result setwhile(rs.next()){// Retrieve by column nameintid=rs.getInt("id");Stringname=rs.getString("name");Stringbranch=rs.getString("branch");intpercent=rs.getInt("percentage");Stringemail=rs.getString("email");// Setting the valuesStudentstudent=newStudent();student.setID(id);student.setName(name);student.setBranch(branch);student.setPercent(percent);student.setEmail(email);list.add(student);}rs.close();returnlist;}}
服务器程序
RMI服务器程序应实现远程接口或扩展实现类。在这里,我们应该创建一个远程对象并将其绑定到RMI注册中心。
以下是此应用程序的服务器程序。在这里,我们将扩展上面创建的类,创建一个远程对象,并使用绑定名称hello将其注册到RMI注册表。
importjava.rmi.registry.Registry;importjava.rmi.registry.LocateRegistry;importjava.rmi.RemoteException;importjava.rmi.server.UnicastRemoteObject;publicclassServerextendsImplExample{publicServer(){}publicstaticvoidmain(Stringargs[]){try{// Instantiating the implementation classImplExampleobj=newImplExample();// Exporting the object of implementation class (here we are exporting the remoteobjectto the stub)Hellostub=(Hello)UnicastRemoteObject.exportObject(obj,0);// Binding the remote object (stub) in the registryRegistryregistry=LocateRegistry.getRegistry();registry.bind("Hello",stub);System.err.println("Server ready");}catch(Exceptione){System.err.println("Server exception: "+e.toString());e.printStackTrace();}}}
客户程序
以下是此应用程序的客户端程序。在这里,我们正在获取远程对象并调用名为getStudents()的方法。它从列表对象中检索表的记录并显示它们。
importjava.rmi.registry.LocateRegistry;importjava.rmi.registry.Registry;importjava.util.*;publicclassClient{privateClient(){}publicstaticvoidmain(String[]args)throwsException{try{// Getting the registryRegistryregistry=LocateRegistry.getRegistry(null);// Looking up the registry for the remote objectHellostub=(Hello)registry.lookup("Hello");// Calling the remote method using the obtained objectListlist=(List)stub.getStudents();for(Students: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(Exceptione){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
上一页 打印页面
下一页