Java Reference
In-Depth Information
The startServer() method creates a WebServer object that monitors that port number
for incoming XML-RPC requests. One handler is added to the server: a DmozHandler
object given the name “dmoz”; then the server's start() method is called to begin lis-
tening for requests.
That's all the code required to implement a functional XML-RPC server. Most of the
work is in the remote methods you want a client to call, which don't require any special
techniques as long as they are public and they return a suitable value.
To give you a complete example you can test and modify to suit your own needs, the
DmozHandler class is provided. The techniques employed in this class were covered dur-
ing Day 18, “Accessing Databases with JDBC,” and are a good review of how to use
JDBC to retrieve records from a database—in this example a MySQL database called
db1 .
Enter the text of Listing 20.5 and save the file as DmozHandler.java ; then compile the
classes DmozServer.java and DmozHandler.java .
LISTING 20.5
The Full Text of DmozHandler.java
1: import java.sql.*;
2: import java.util.*;
3:
4: public class DmozHandler {
5: public Vector getRandomSite() {
6: Connection conn = getMySqlConnection();
7: Vector<String> response = new Vector<String>();
8: try {
9: Statement st = conn.createStatement();
10: ResultSet rec = st.executeQuery(
11: “SELECT * FROM cooldata ORDER BY RAND() LIMIT 1”);
12: if (rec.next()) {
13: response.addElement(“ok”);
14: response.addElement(rec.getString(“url”));
15: response.addElement(rec.getString(“title”));
16: response.addElement(rec.getString(“description”));
17: } else {
18: response.addElement(“database error: no records found”);
19: }
20: } catch (SQLException sqe) {
21: response.addElement(“database error: “ + sqe.getMessage());
22: }
23: return response;
24: }
25:
26: private Connection getMySqlConnection() {
27: Connection conn = null;
20
Search WWH ::




Custom Search