Acting as an RMI Client

In Chapter 10, we saw how a servlet can act as an RMI server. Here we turn the tables and see a servlet acting as an RMI client. By taking the role of an RMI client, a servlet can leverage the services of other servers to accomplish its task, coordinate its efforts with other servers or servlets on those servers, and/or act as an proxy on behalf of applets that can’t communicate with RMI servers themselves.

Example 13.8 shows DaytimeClientServlet, a servlet that gets the current time of day from the DaytimeServlet RMI server shown in Chapter 10.

Example 13-8. A servlet as an RMI client

import java.io.*; import java.rmi.*; import java.rmi.registry.*; import javax.servlet.*; import javax.servlet.http.*; public class DaytimeClientServlet extends HttpServlet { DaytimeServer daytime; // Returns a reference to a DaytimeServer or null if there was a problem. protected DaytimeServer getDaytimeServer() { // Set the security manager if it hasn't been done already. // Provides protection from a malicious DaytimeServer stub. if (System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); } try { Registry registry = LocateRegistry.getRegistry(getRegistryHost(), getRegistryPort()); return (DaytimeServer)registry.lookup(getRegistryName()); } catch (Exception e) { getServletContext().log(e, "Problem getting DaytimeServer reference"); return null; } } private String getRegistryName() { String name = getInitParameter("registryName"); return ...

Get Java Servlet Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.