Client Implementation
Listing 12.3
ClientServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.rmi.*;
//client implementation
public class ClientServlet
extends HttpServlet{
//reference to the remote server
private ServerHandlerInterface obj;
//Initialize the servlet and log the initialization.
public void init(ServletConfig c)
throws ServletException{
super.init(c);
try{
//get a remote reference
obj = (ServerHandlerInterface)Naming.lookup("Server");
}catch(Exception ex){
System.out.println("Error: " + ex.getMessage());
}
}
//Perform the HTTP GET operation
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
//get the name of the user
String name = req.getParameter("username");
String result = null;
try{
//Call remote method
result = obj.servletTest(name);
}catch(Exception ex){
result = "Error : " +ex.getMessage();
}
//Set the content type for this response object.
res.setContentType("text/html");
//get a print writer for writing formatted text responses
PrintWriter out = res.getWriter();
//Print a String and then terminate the line
out.println("<Html><Body><H1>RMI AND SERVLETS</H1>");
out.println(result+"</Body></Html>");
}
}
Explanation
The init() method is
called once, automatically, by the network service each time it loads
the servlet. It is guaranteed to finish before any service requests
are accepted. First, the init()
method calls the super.init()
and then it gets a reference to the remote object.
The doGet() method is called by the
default implementation of the service()
method in the response to an HTTP request. If an HTTP get
request is received, this method will be called.
The method gets the name of the user and calls the remote servletTest()
method. After getting the result, it creates a small web page that will
be shown to user.
|