servlet as a client for RMI

I want to write a servlet which will actually be the client for RMI.
where shall I put the code in the servlet? for example: the following is the code for creating RMI client

try{
RemoteInterface server = (RemoteInterface)Naming.lookup("ServerTest");

serverString = server.message("Hello there");
System.out.println("The server says:\n " + serverString);
}
catch (Exception e)
{
System.out.println("Error while performing RMI");
}
if I want to put this in a servlet,should I put it in the init() method or somewhere else?
are there any other changes that have to be done? Please give me a code example.
twgAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

heyhey_Commented:
you can put this code everywhere ...
0
twgAuthor Commented:
Thanks heyhey but putting this code (at least in init() method) doesn't work.
It throws an exception and prints to the dos window "Error while performing RMI".You probably know the "hello there" so i want that the client will print his message on the browser (using the servlet).
0
mbormannCommented:
http://www.servlets.com/jsp/examples/ch13/index.html

Hope u like Jason Hunter's excellent source code ,I suggest you buy the book
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

mbormannCommented:
0
Ravindra76Commented:
Hi twq,

1. IF you want RMI call for every server request thread,the remote method is to be invoked put it in service(or doGet() or doPost() or any..).

2.If you think, RMI call only once, put it in inti() method.

It is your application strategy.

Best of luck
0
twgAuthor Commented:
Thanks heyhey but putting this code (at least in init() method) doesn't work.
It throws an exception and prints to the dos window "Error while performing RMI".You probably know the "hello there" so i want that the client will print his message on the browser (using the servlet).
0
heyhey_Commented:
replace

catch (Exception e)
{
System.out.println("Error while performing RMI");
}

with
catch (Exception e)
{
  e.printStackTrace();
}


and post here the full exception stacktrace
0
mbormannCommented:
hey sorry I had not meant to answer but only comment,feel freet o reject it.
0
twgAuthor Commented:
thanks everyone. I checked the examples from the book and I changed few lines in my code but still it doesn't work and throws the exception. therefor I enclose my code and if you can tell me what's wrong with it, I'll be gratefull.

the RMI server:
----------------
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.registry.*;



//creating an implementing class
public class RemoteObject extends UnicastRemoteObject implements RemoteInterface
{
String name;
public RemoteObject (String name) throws RemoteException
{
      super();
      this.name = name;
}
      
public String message (String message) throws RemoteException
{
String rs = "My name is:" + name + ",thanks for your message:" + message;
System.out.println ("Returning:" + rs);
return  "My name is:" + name + ",thanks for your message:" + message;
}
      
      
public static void main (String args[])
{
try{
//create the registry on port 1099
Registry reg = java.rmi.registry.LocateRegistry.createRegistry(1099);
String myName = "ServerTest";
RemoteObject theServer = new RemoteObject (myName);
Naming.rebind(myName, theServer);
System.out.println ("Ready to continue");
}
catch (Exception e)
{
System.out.println ("an exception occured while creating server"+ e);
}
}//end of main
      
}//end of class

the RMI client (which is actually a servlet):
-------------------------------------
import java.io.*;
import javax.servlet.*;
import java.rmi.*;
import java.rmi.registry.*;
import javax.servlet.http.*;


public class RemoteClient implements Servlet {
      
private ServletConfig config;
private String serverString;
RemoteInterface server;
            
public void init (ServletConfig config) throws ServletException {
            
this.config = config;
try{
Registry registry = LocateRegistry.getRegistry();
RemoteInterface server = (RemoteInterface)registry.lookup("ServerTest");
serverString = server.message("Hello there");
System.out.println( "The server says:\n " + serverString);
}
catch (Exception e)
{
System.out.println("Error while performing RMI");
}                        }
                  
}//end of init
      
public void destroy() {}
      
public ServletConfig getServletConfig() {
      return config;
}//end of destroy
      
public String getServletInfo() {
return "A Simple servlet";
}//end of getServletInfo
      
public void service (ServletRequest req, ServletResponse res)
throws ServletException, IOException {
                  
res.setContentType ("text/html");
PrintWriter out = res.getWriter();
out.println ( "<html>" );
out.println ( "<head>" );
out.println ( "<title>A Sample Servlet</title>" );
out.println ( "</head>" );
out.println ( "<body>" );
out.println ( "<h1>A Servlet as a RemoteClient</h1>" );
out.println ( "<h1>The server says:\n" +serverString+ "</h1>");
out.println ( "</body>" );
out.println ( "</html>" );
out.close();
}//end of service

}                  
            
            
                  
                                                      
0
twgAuthor Commented:
thanks everyone. I checked the examples from the book and I changed few lines in my code but still it doesn't work and throws the exception. therefor I enclose my code and if you can tell me what's wrong with it, I'll be gratefull.

the RMI server:
----------------
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.registry.*;



//creating an implementing class
public class RemoteObject extends UnicastRemoteObject implements RemoteInterface
{
String name;
public RemoteObject (String name) throws RemoteException
{
      super();
      this.name = name;
}
      
public String message (String message) throws RemoteException
{
String rs = "My name is:" + name + ",thanks for your message:" + message;
System.out.println ("Returning:" + rs);
return  "My name is:" + name + ",thanks for your message:" + message;
}
      
      
public static void main (String args[])
{
try{
//create the registry on port 1099
Registry reg = java.rmi.registry.LocateRegistry.createRegistry(1099);
String myName = "ServerTest";
RemoteObject theServer = new RemoteObject (myName);
Naming.rebind(myName, theServer);
System.out.println ("Ready to continue");
}
catch (Exception e)
{
System.out.println ("an exception occured while creating server"+ e);
}
}//end of main
      
}//end of class

the RMI client (which is actually a servlet):
-------------------------------------
import java.io.*;
import javax.servlet.*;
import java.rmi.*;
import java.rmi.registry.*;
import javax.servlet.http.*;


public class RemoteClient implements Servlet {
      
private ServletConfig config;
private String serverString;
RemoteInterface server;
            
public void init (ServletConfig config) throws ServletException {
            
this.config = config;
try{
Registry registry = LocateRegistry.getRegistry();
RemoteInterface server = (RemoteInterface)registry.lookup("ServerTest");
serverString = server.message("Hello there");
System.out.println( "The server says:\n " + serverString);
}
catch (Exception e)
{
System.out.println("Error while performing RMI");
}                        }
                  
}//end of init
      
public void destroy() {}
      
public ServletConfig getServletConfig() {
      return config;
}//end of destroy
      
public String getServletInfo() {
return "A Simple servlet";
}//end of getServletInfo
      
public void service (ServletRequest req, ServletResponse res)
throws ServletException, IOException {
                  
res.setContentType ("text/html");
PrintWriter out = res.getWriter();
out.println ( "<html>" );
out.println ( "<head>" );
out.println ( "<title>A Sample Servlet</title>" );
out.println ( "</head>" );
out.println ( "<body>" );
out.println ( "<h1>A Servlet as a RemoteClient</h1>" );
out.println ( "<h1>The server says:\n" +serverString+ "</h1>");
out.println ( "</body>" );
out.println ( "</html>" );
out.close();
}//end of service

}                  
            
            
                  
                                                      
0
mbormannCommented:
have u checked the Example pointed ?
0
twgAuthor Commented:
what do you mean "the example pointed"?
0
twgAuthor Commented:
I have checked this example and as I said before - I changed a few lines according to this example but it still doesn't work and that's why I sent to you my code so you can tell me what's wrong with it.
0
twgAuthor Commented:
by the way, the following is the full stacktrace:
:java.rmi.UnmarshalException: error unmarshalling return; nested exception is
java.lang.ClassNotFoundException: RemoteObject_Stub
java.lang.ClassNotFoundException: RemoteObject_Stub)
at java.io.ObjectInputStream.inputObject(ObjectInputStream.java:981)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:232)
at com.sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at RemoteClient.initRemoteClient.java:21
)
at com.sun.web.core.ServletWrapper.loadServlet(ServletWrapper.java:91
at com.sun.web.core.ServletWrapper.handleRequest(ServletWrapper.java:109)
)
at com.sun.web.core.InvokerServlet.service(InvokerServlet.java:169)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:840
at com.sun.web.core.ServletWrapper.handleRequest(ServletWrapper.java:140)
)at com.sun.web.core.Context.handleRequest(Context.java:375)
at com.sun.web.server.ConnectionHandler.run(ConnectionHandler.java:135

at(Context.java:375)
        at com.sun.web.server.ConnectionHandler.run(ConnectionHandler.java:135)

0
Ravindra76Commented:
Hi Twg,

Hav you followed all the steps in sequnece.

1.Compiling Remote Interface.(Which extends Remote interface )
2.Compiling Remote Server (which implements that remote interface)
3.Using rmic for RemoteServer.
4.Copying the stub and remote interface to client side.
5.Compiling Remote Client
6.Startingf RMI registry on server side.
7.Running RMI client.

Error:_

From the stack trace, it is clear that
Stub is not presented on Client side.

That's all.

Best of luck
0
twgAuthor Commented:
Thank you vey much ravindra76. you were right. Th estub was missing on the client side.
Thank you very much again.
0
mbormannCommented:
Hey Ravi answerd and u gave me points!

Man he should have got those,

Ravi if he doesnt post it due to any reason I will ask Customer Service to post a dummy question for you.

Regards
0
Ravindra76Commented:
Hi Amit,

 No Problem.

 Main goal: Clarifying the doubt was successful.

Thank you
0
mbormannCommented:
no no,
thanks for reminding me but I will right now send a mail to IanB or Linda.
0
twgAuthor Commented:
Thank you all again and I hope the points will go to the right person.
The problem was that Ravindra76 answered in a "Comment" and not in the "Answer" textbox.
sorry for the mess.
0
mbormannCommented:
dont worry I have sent a Email to IanB right now.
he would most probably post a 50 point question in Java for ravindra76.
0
twgAuthor Commented:
Thanks again and bye for now(untill the next question).
0
ianBCommented:
Hi,

I have been directed to this question by mbormann regarding allocating points. To rectify this, I have posted a question (Q.10250143) for ravindra76 in this topic area, so he can claim the points for this question.

Ian
Community Support @ Experts Exchange
0
heyhey_Commented:
'Hi Amit,
 No Problem.
 Main goal: Clarifying the doubt was successful.
Thank you'

that's nice :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.