java rmi数据库_Java RMI数据库应用程序

Java RMI - Database Application

In the previous chapter, we created a sample RMI application where a client invokes a method which displays a GUI window (JavaFX).

In this chapter, we will take an example to see how a client program can retrieve the records of a table in MySQL database residing on the server.

Assume we have a table named student_data in the database details as shown below.

+----+--------+--------+------------+---------------------+

| 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 |

+----+--------+--------+------------+---------------------+

Assume the name of the user is myuser and its password is password.

Creating a Student Class

Create a Student class with setter and getter methods as shown below.

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;}}

Defining the Remote Interface

Define the remote interface. Here, we are defining a remote interface named Hello with a method named getStudents () in it. This method returns a list which contains the object of the class Student.

importjava.rmi.Remote;importjava.rmi.RemoteException;importjava.util.*;// Creating Remote interface for our applicationpublicinterfaceHelloextendsRemote{publicListgetStudents()throwsException;}

Developing the Implementation Class

Create a class and implement the above created interface.

Here we are implementing the getStudents() method of the Remote interface. When you invoke this method, it retrieves the records of a table named student_data. Sets these values to the Student class using its setter methods, adds it to a list object and returns that list.

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;}}

Server Program

An RMI server program should implement the remote interface or extend the implementation class. Here, we should create a remote object and bind it to the RMI registry.

Following is the server program of this application. Here, we will extend the above created class, create a remote object and register it to the RMI registry with the bind name hello.

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();}}}

Client Program

以下是本应用程序的客户端程序。在这里,我们正在获取远程对象并调用名为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

db92cd344df68aad8faf051d6df5468d.png

步骤2-使用以下命令启动rmi注册表。

start rmiregistry

abf3a08593425d820e1d295de4727796.png

这将在单独的窗口中启动一个rmi注册表,如下所示。

55a571c39e286b92004870fd341b0b51.png

步骤3- 运行服务器类文件,如下所示。

Java Server

5ed291b970eb19c9753b504f2bebcb1a.png

步骤4- 运行客户端类文件,如下所示。

java Client

client_file.jpg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值