Applet-Servlet Communication and Information Sharing

glueblacksmithInternet και Εφαρμογές Web

13 Νοε 2013 (πριν από 4 χρόνια και 1 μήνα)

108 εμφανίσεις

Applet-Servlet Communication and Information Sharing
J2EE Professional Skills Development 5-1
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


Applet-Servlet
Communication
and Information
Sharing
Objectives
• Look at applet and servlet communciation.
• Learn about Remote Method Invocation.
• Examine servlet to servlet sharing.
• Use servlets in an Enterprise environment.

Applet-Servlet Communication and Information Sharing
5-2 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

Applet-Servlet Interaction
An applet is a component that exists and operates in the client tier; the servlet
can act as a bridge to the Web application or a stand-alone component offering
services. Applets allow another form of component encapsulation and there are
many applets available for business or pleasure on the Internet (one such site is
http://www.javashareware.com/
). Whether you use applets, JavaBeans, or
servlets depends on their function and what tier you want these components to
operate through. For example, there are applets that set up menus and toolbars,
offer a wide range of financial calculators, do advanced charting, and show
stock market prices.
Communication Choices
There are many means of communication, and the two most common are
through the Internet and an internal network or intranet. An internal network
has specific communication channels that it must use and these channels are
often proprietary to the network operating system. The Internet offers a wide
range of communication protocols, the most common being FTP (File Transfer
Protocol) and HTTP (Hypertext Transfer Protocol).
Applets that Are Trusted and Untrusted
When using the applet tag within an html page, applets can function as either normal
applications and have full rights on the client browser and machine, or they can utilize
a digital signature method signed by someone the user trusts. This marks the source of
the applet and ensures that it does not change during transmission. Even so, a trusted
applet can be partially or fully trusted by granting specific privileges and rights.
The methods of communication for applets and servlets are either HTTP or
socket.
HTTP Communication
Using HTTP, the normal request/response model plus utilization of query
strings is POSTS and GETS. Most developers are familiar with this model and
it has been discussed in previous chapters extensively. It is simple and the
java.net.URL and java.net.URLConnection classes can be utilized for full
functionality. HTTP communication works with secure connections (HTTPS),
transmits over port 80 so there are no firewall concerns (port 80 is a default for
many Web servers, and this port on a router is typically left open for incoming
network traffic), and works with all browsers and programs written in any
language. Now for the bad news: the applet must begin the communication and
Applet-Servlet Interaction

J2EE Professional Skills Development 5-3
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


everything must wait for it. There are no typical responses because they must
be formatted using pre-established standards. This issue of formatting
responses is not as bad as you might think; with object serialization, the applet
and servlet can communicate by trading Java objects and the objects do not
need to be identical types. The query string’s HTTP communication needs are
ungainly as they use arrays. This type of communication is extremely slow
requiring a new communication path for every response and request. HTTP is
the typical method of communication used by most developers, because of its
ease of use with any browser and firewall.
Socket Communication
Socket communication is the typical networking communication method. It is
very efficient running on the server end and responses can be issued
instantaneously. Socket communication is bi-directional and continuous. The
applet must still begin the contact process, but the client or the server can write
to the socket whenever appropriate. Though socket communication offers
greater flexibility, this method is not often used unless necessary because of its
complexity.
Remote Method Invocation (RMI)
RMI is another communication option where a servlet can call up or invoke
methods of any Java object on the server. It is also an opportunity for the
server objects to invoke applet methods. RMI utilizes the full power of object
orientation; requests can pass in object parameters (serialized of course) and
responses can be received as objects. Under RMI there are no actual requests
and responses as used by HTTP, there are just method calls or invocations with
objects being sent. This method works through firewalls brilliantly, because
while the RMI layer operates via direct socket connections, it can function
completely within HTTP as needed and can do it automatically.
RMI can be quite complicated and each remote object needs coding besides
having to set up a special naming registry where all references to the remote
objects are maintained. Only Netscape Navigator 4 or above support RMI and
other browsers must first set up a plug-in. Also, RMI is strictly Java and can
only be used by Java programs.
RMI is there to extend the Java object model to the network and make the
locality of the server transparent to the client. Unlike HTTP request/response,
there is the issue of formatting and translating the communication; at the
hardware level, only zeros and ones are recognized, so marshalling and
serialization are used to pack, convert, and transfer the messages. RMI needs
more class metadata per call for rebuilding objects. There is also a need for the
request to be fully serviced rather than merely processed (just a response
generated); the servicing could involve querying another source and
computations.
Applet-Servlet Communication and Information Sharing
5-4 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

Key Terms
Marshalling The process of unpacking client requests and converting them
into objects to send to back-end application servers.
Serialization The process of converting objects into zeroes and ones. This
allows objects to be written to a stream and then recalled at a
later time.
The RMI API
The RMI package, javax.rmi, is absolutely uncomplicated; there is only one
class within it, the class PortableRemoteObject. This class has a constructor
and the five methods shown in Table 1.
Return Type Method Description
static void connect(java.rmi.Remote target,
java.rmi.Remote source)
Gets the Remote object set
for remote communication.
static void exportObject(java.rmi.Remote obj) Sets the server object to
receive remote calls.
static void unexportObject(java.rmi.Remote obj) Deregisters the server object
so the object is available for
garbage collection.
static java.lang.Object toStub(java.rmi.Remote obj) Returns a stub for the server
object.
static java.rmi.Remote narrow(java.lang.Object narrowFrom,
java.lang.Class narrowTo)
Ensures that an object of a
remote type can be cast to
the desired type.
Table 1. The API for the RMI PortableRemoteObject.
There is another aspect to RMI that needs to be examined, CORBA. CORBA
(Common Object Request Broker Architecture) communicates between
distributed objects written in any language. CORBA has a specific
communication protocol, IIOP (Internet Inter-ORB Protocol), where the
communication works on any language’s objects. A full examination of both
CORBA and IIOP would take a full week in itself, but here is a look at the API
shown in Table 2.
Applet-Servlet Interaction

J2EE Professional Skills Development 5-5
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


Interface/Class Description
PortableRemoteObjectDelegate Interface Allows delegation for method implementations in
PortableRemoteObject.
StubDelegate Interface Allows delegation for method implementations in Stub.
Tie Interface Defines methods all RMI-IIOP server-side ties must
implement.
UtilDelegate Interface Allows delegation for method implementations in Util.
ValueHandler Interface Allows methods for serialization of Java objects to and from
GIOP streams.
ClassDesc Class Marshals java.lang.Class objects over IIOP.
Stub Class Defines the base class all RMI-IIOP stubs must inherit.
Util Provides utility methods for use by stubs and ties to do
common operations.
Table 2. The API for javax.RMI.CORBA.
RMI can also communicate with JRMP (Java Remote Messaging Protocol)
and it should not matter which protocol is used. JRMP is the native protocol
used to access EJB (Enterprise Java Beans). CORBA gives the advantage of
the RMI interface for distributed systems programming with the CORBA
architecture, plus the ability to interact with non-Java clients and servers.
The client doesn’t know, or care, where the server objects are under RMI;
there are 17 different Java Virtual Machines (JVM) for the various operating
system platforms where Java can operate and RMI ensures location
transparency for the server objects. An object can run in a remote JVM (the
server) or the client’s JVM. The parameters passed into a method can also be
complex objects that are passed in by value as a solitary argument (e.g., a hash
table or vector holding references to many elements); the object is resolved,
serialized and passed to the remote method. Remote objects are never passed
by value, they are passed by reference as this ensures uniqueness in a
distributed environment. The client then uploads the behavior or method from
the server by simple method invocation. RMI also allows the possibility to off-
load computation from the server to the client, while keeping a central code
base. RMI has secure channels and is able to isolate the downloaded
implementations inside of a secure sandbox (the security mechanism for
applets and Java code running in the client environment). RMI can connect to
applications and legacy systems in other languages using JNI (Java Native
method Interface) as a bridge. RMI over JNI and RMI over JDBC can be used
to connect to databases.
A further model is the ROA (Remote Object Activation model), where servers
can create remote objects on demand rather than at the server startup. This
frees resources until they are needed, plus clients can keep references to these
remote objects without necessitating them to be continually executing.
Applet-Servlet Communication and Information Sharing
5-6 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

The RMI Process
1. The client must locate the remote object. The server application registers
the object with the RMI registry using a naming service.
2. The client communicates with the remote object. Under RMI, this process
appears to be a normal method invocation with return values.
3. Classes must be loaded for objects that are passed as parameters or return
values. Both the client and server may receive embedded objects, but they
do not have the subsequent class files; RMI provides the means to load an
object’s class files.
The overall process is shown in Figure 1.

Figure 1. The RMI process.
The RMI Pieces
RMI contains many components including the remote interface, remote object
class, stubs, skeletons, the registry, and local objects. All of the components
are necessary, some being hosted on the local machine and some on the remote
machine.
The Remote Interface is a set of business methods called by the client upon a
remote object. The interface is the means by which the client interacts with the
remote object.

Applet-Servlet Interaction

J2EE Professional Skills Development 5-7
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


public interface cart extends java.rmi.Remote {
public void putInCart (int quantity) throws
java.rmi.RemoteException;
public void removeFromCart (int quantity) throws
java.rmi.RemoteException;
}
The Remote Object Class implements the server-side methods. At a minimum,
it implements the methods in the remote interface, but other methods may not
be available to remote clients.

public class cartNow extends UnicastRemoteObject
implements cart {
public void putInCart (int quantity) throws
java.rmi.RemoteException {
//Your code goes here }
public void removeFromCart (int quantity) throws
java.rmi.RemoteException {
//Your code goes here }
}
Stubs and Skeletons are the mechanisms that communicate with the remote
object. A stub for a remote object is a representative or proxy for the remote
object. The client invokes the method on the stub, which connects to the
remote object JVM, passes the method call and parameters, waits for the
remote method to return, and maybe passes back a result to the client. The stub
for remote objects implements the same interface that the remote object does.
The stub is really a part of the ORB (Object Request Broker), which is the
actual communication facilitator. On the server side, the ORB uses the
skeleton to translate the call and parameters, and it does the calling. The
skeleton then transforms results or exception errors and returns them to the
client via ORB. The skeleton is the server-side analogy of the client stub.
The Registry keeps the references to the remote objects and provides the
methods that look up the references by a URL. The server must register the
object and provide an alias name. If the server shuts down, all references in the
registry are cleared and must be re-registered upon server startup.

Naming.rebind ("//<host-name>/myCart", new cartNow());

The local objects are the client-side objects that invoke the method calls. They
request the references from the registry and issue the method call on the stub.
Applet-Servlet Communication and Information Sharing
5-8 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


cart thisCart = null;
try {
thisCart = (cart)Naming.lookup ("//" +
getCodeBase().getHost() + "/myCart");
thisCart.putInCart(23);
} catch (Exception e) {
//do exception handling here }

Putting it all together, here is the code that deals with the RMI registry:

import java.io.*;
import java.net.*;
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class RemoteAccess extends HttpServlet implements
Remote {
/* note that it did not extend UnicastRemoteObject as the
example previously did. Java supports single inheritance
so you must choose between HttpServlet and
UnicastRemoteObject. It is easier to write in the
operations of UnicastRemoteObject than HttpServlet but the
Remote interface must also be implemented because
UnicastRemoteObject included this functionality when it is
extended */
protected Registry registry;

public void init (ServletConfig config) throws
ServletException {
super.init(config);
try {
UnicastRemoteObject.exportObject(this);
Applet-Servlet Interaction

J2EE Professional Skills Development 5-9
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


/* Again, when UnicastRemoteObject is the superclass, the
exporting is not an issue but here it must be physically
done to export itself */
bind(); //register
}
catch (RemoteException e) {
getServletContext().log(e, "Problem!! ");
}
}
public void destroy() {
unbind() //unregister }

public void bind() {
try
registry = LocateRegistry.getRegistry(getPort());
/* The code tries to get or locate the registry running on
the port found by the getPort method */
registry.list(); //make sure registry is up
}
catch (Exception e) {
registry = null; //couldn’t set registry
}
if(registry == null) {
try {
registry =
LocateRegistry.createRegistry(getPort()); }
/* if the registry is not there, it will be created at the
port determined by the getPort method */
catch (Exception e) {
log("something is really bad" + getPort() +
e.getMessage());
return;
}
}
try {
registry.rebind(getName(), this);
/* the servlet binds itself to the newly created registry
using rebind to replace any previous entries */
Applet-Servlet Communication and Information Sharing
5-10 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

}
catch (Exception e) {
log("no binding today?$#@ " + e.getMessage());
}
}
public void unbind() {
try {
if(registry != null)
registry.unbind(getName());
}
catch (Exception e) {
getServletContext().log ("problem getting out of
here and unbinding this thing" + e.getMessage());
}
}
public String getName() {
/* This method finds the name under which the servlet
should be registered by pulling in the init parameter
registryName */
String name = getIniParameter("registryName");
if (name != null) return name;

return this.getClass().getName();
/* if there is a problem getting the registered name, a
default is chosen as the servlet’s class name */
}
public int getPort() {
/* This method finds the port on which the servlet is
running which is found from the init parameter
registryPort */
try {
return
Integer.parseInt(getInitParameter("registryPort"));
}
catch (NumberFormatException e) {
/* if an exception is encountered in finding the
registryPort parameter, default to port 1099, the default
registry port */
Applet-Servlet Interaction

J2EE Professional Skills Development 5-11
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


return Registry.REGISTRY_PORT;
}
}
}

So far, code has been established, under the remoteAccess class, to export and
register a component. A shell interface is then set up that the actual servlet will
be built on.

import java.rmi.remote;
import java.rmi.RemoteException;

public interface Information extends Remote {
public String getFullName() throws RemoteException;
public String getAddress() throws RemoteException;
}

It is just a simple interface that provides for two methods that will be accessed
remotely by clients. It must be done so that the Remote interface is extended
and the servlet is readied for remote calling. Here is the actual servlet code:

import java.io.*;
import java.net.*;
import java.util.*;
import java.servlet.*;
import java.servlet.http.*;

import remoteAccess;
/* the exporting and registering class previously written
*/

public class InformationServlet extends remoteAccess
implements Information {

public String getFullName()
return String("Barry Solomon");
public String getAddress()
Applet-Servlet Communication and Information Sharing
5-12 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

return String("Reno, NV");
}
public void init (ServletConfig config) throws
ServletException {
super.init(config);
}
public void doGet (HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException {
if ("object".equals(req.getParamter("format")))
/* the user has asked this to be formatted as an object */
{
ObjectOutputStream out = new
ObjectOutputStream(res.getOutputStream());
out.writeObject(getFullName());
out.writeObject(getAddress());
}
else {
PrintWriter out = res.getWriter();
out.println(getFullName());
out.println(getAddress());
/* user did not ask for it to be an object, make it ASCII
*/
public void doPost (HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException {
goGet(req, res);
}
/* either a doGet or a doPost return the same information
*/
public void destroy() {
super.destroy();
}
}
The servlet coding is finished but, after it is compiled normally using the Java
compiler (javac), it must be compiled again using the RMI rmic compiler to
generate the stub and skeleton versions of the class. Just give the class name;
no files should be put there.
Applet-Servlet Interaction

J2EE Professional Skills Development 5-13
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.



c:>/ rmic InformationServlet

If the servlet is part of a package use:

c:>/ rmic package.name.InformationServlet

There should now be a _Stub.class and a _Skel.class. The stub and skeleton
classes only need to be created anew if you change the interface that the servlet
uses. The applet will need a few files available in the server’s document root
area: the stub class and the interface class. Both of these files are used for
communication between the applet and the servlet. The servlet also needs
access to these classes so the files should be in the server’s classpath. All the
classes, except for the applet class, should be under the server_root classes
area. The stub class, the interface class, the applet class, and the html page
should be under the server_root/webapps/root.
The final class to account for is the applet itself:

import java.rmi.*;
import java.rmi.registry.*;

private String getHost() {
return getCodeBase().getHost();
}

private int getPort() {
try ( return
Integer.parseInt(getParameter("registryPort")); }
catch (NumberFormatException e) {
return Registry.REGISTRY_PORT; }
)

Private String getName() {
String name = getParameter("registryName");
if (name == null) {
name = "InformationServlet";
}
return name;
Applet-Servlet Communication and Information Sharing
5-14 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

}

private String getFullNameRMI() {
try {
Registry registry =
LocateRegistry.getRegistry(getHost(), getPort());
/* this is the actual lookup to the registry itself at
this port and host */
Information info =
(Information)registry.lookup(getName());
/* here is the lookup in the registry of the remote
servlet object registered under the name and it casts it
to an information object */
return info.getFullName();
/* here is the method invocation of the remote servlet
object’s getFullName method */
}
catch (ClassCastException e) {
System.out.println("HELP ME" + e.getMessage());
}
catch (NotBoundException e) {
System.out.println(getName()+"not bound" +
e.getMessage());
}
catch (RemoteException e) {
System.out.println(e.getMessage());
}
catch (Exception e) {
System.out.println("bad things happening" +
e.getClass().getName() + e.getMessage());
}
return null;
}




Applet-Servlet Interaction

J2EE Professional Skills Development 5-15
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


NOTE The registry server is typically run with the standalone rmiregistry
program. In the previous code example, the remoteAccess servlet
creates the registry and this is a preferred way of doing it because
it’s more efficient and simpler. This way the registry is created
when needed and runs in the same JVM as the servlet and the
server itself.
Applet-Servlet Communication and Information Sharing
5-16 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

Servlet to Servlet Communication
Servlets share information such as state (fields or properties) and resources
such as database connections. Servlets can also share control of a request or
divide request tasks.
Information Distribution
One of the primary ways of sharing is through the ServletContext, which was
examined in an earlier chapter. Some of the API is shown in Table 3.

Return Type Method Description
java.lang.Object getAttribute(java.lang.String.name) Returns the specific attribute.
java.util.Enumeration getAttributeNames() Returns an Enumeration with all the
names in this servlet context.
ServletContext getContext(java.lang.String uripath) Returns the ServletContext for a URL.
java.lang.String getInitParameter(java.lang.String name) Returns a string for the specific
context-wide initialization parameter.
java.util.Enumeration getInitParameterNames() Returns an Enumeration of all this
context’s initialization parameter.
void removeAttribute(java.lang.String name) Removes this specific attribute from
the servlet context.
void setAttribute(java.lang.String name,
java.lang.Object object)
Sets this attribute in the servlet
context.
java.lang.String getRealPath(java.lang.String path) Returns the real path for a virtual
path.
RequestDispatcher getRequestDispatcher(java.lang.String
path)
Returns a RequestDispatcher that
wraps the resource at this path.
java.net.URL getResource(java.lang.String path) Returns the URL for a resource.
java.io.InputStream getResourceAsStream(java.lang.String
path)
Returns the resource as an
InputStream object.
java.lang.String getServerInfo() Returns the name and version of the
servlet container that the servlet is
running on.
void log(java.lang.String msg) Writes message to a servlet log file.
Table 3. A part of the API for ServletContext.

Servlet to Servlet Communication

J2EE Professional Skills Development 5-17
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


Here is a basic servlet that provides information about an employee:

import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class theGoods extends HttpServlet {
public void doGet (HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException {
res.setContextType ("text/html");
ServletContext context = getServletContext();
context.setAttribute("FullName", "Barry Solomon");
context.setAttribute("Position", "Supervisor");
out.println
("<html><header><title>Super</title></header>");
out.println ("<body> Here is the
stuff</body></html>");
}

}

That is the special information that all the other servlets must have. Here is the
servlet that pulls in the above information:

Applet-Servlet Communication and Information Sharing
5-18 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

import java.util.*;
import java.io.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class copyCat extends HttpServlet {
public void doGet (HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException {
res.setContextType ("text/html");
PrintWriter out = res.getWriter();
ServletContext context = getServletContext();
String FullName = context.getAttribute("FullName");
String Position = context.getAttribute("Position");
out.println("Here is the information you requested: " +
FullName + " " + Position); }

A ServletContext may share with another; remember, each Web application
maintains its own information and ServletContext. If a servlet needs
information outside of itself via another Web application’s ServletContext, it
takes this form:

public ServletContext
ServletContext.getContext(String.uripath)

The actual implementation for the previously looked at information servlet
might look like the following:

ServletContext context = getServletContext();
ServletContext externalContext =
context.getContext("/informationsite/index.html");
String FullName =
externalContext.getAttribute("FullName");
String Position =
externalContext.getAttribute("Position");

Servlet to Servlet Communication

J2EE Professional Skills Development 5-19
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


One further problem that needs addressing is that the context could contain an
object that the class does not recognize as it does not have the class files for
that object. In the deployment descriptor file, web.xml, all the classes for every
Web application are maintained so a class loader will not find class files from
another application and an exception will be generated. The easiest solution is
to copy the class files for the shared object into the server’s classpath.
Control Distribution
One servlet can forward or include an entire request to another servlet, or it can
build its response as a compilation of materials produced by other servlets and
other Web applications. There is also the idea of redirection by using the
sendRedirect() method where the client is actually sent elsewhere and forces
roundtrip messaging with the client.
Forwarding
The forward() method, sends the request somewhere else on the server so one
servlet can begin processing and another creates the response itself. The client
never knows this is happening—it is transparent since it occurs within the
JVM of the one servlet container and information is sent using a query string
or the setAttributes() method.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class findAndSeek extends HttpServlet {
public void doGet (HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException {
String Find = req.getParameter("Find");
String[] Goods = getResults("Find");

req.setAttribute("Goods", Goods);

String Show = "/servlet/Show";
RequestDispatcher dispatch =
req.getRequestDispatcher(Show);
dispatch.forward(req, res);
String[] Goods = getResults("Find");
Applet-Servlet Communication and Information Sharing
5-20 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

return new String[] ("Whatever the results were of the
finding and seeking");
}
}
The RequestDispatcher interface is being used here and its forward method is
being invoked. The RequestDispatch has just two methods as shown in the
API in Table 4.
Return Type Method Description
void forward(ServletRequest req, ServletResponse res) Forwards the request from this servlet
to another servlet, JSP file, or HTML
file on the server.
void include(ServletRequest req, ServletResponse res) Includes the content of another
servlet, JSP file, or HTML file in the
response.
Table 4. The API for the RequestDispatcher object.
This forwards the request to the Show servlet. There are a few rules to be
aware of when using forwarding from a servlet:
• The servlet can set status codes and headers, but cannot send a
response body back to the client so a forward() is used before a
response is committed.
• Do not ever replace the request and response with new versions.
Forward must be called with the identical request and response that
were passed and must use the same thread.
• If the response hasn’t been committed and there is content in its buffer,
that is cleared during the forward.
• If the response is committed, the forward throws an exception.
The servlet that the previous servlet forwarded to is shown in the following
code:

Servlet to Servlet Communication

J2EE Professional Skills Development 5-21
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Show extends HttpServlet {
public void doGet (HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException {
res.setContentType = ("text/html");
PrintWriter out = res.getWriter();

String[] Goods = (String[]) req.getAttribute("Goods");
out.println ("Here they are - ");
for (int i; i<Goods.length; i++) {
out.println(Goods[i]);
}
}
out.println(req.getServletPath());
out.println(req.getContextPath());
out.println(req.getRequestURI());
out.println(req.getQueryString());
}
}

Including
The include method places the content of the external resource inside of the
calling servlet’s response, similar to an include in other technologies. The
servlet making the call manages the response. An include may be used
anywhere, as it cannot alter status codes or headers.
WARNING! Do not try to substitute request and response objects—the same ones
must be used throughout because both servlets will utilize the same
thread.

Applet-Servlet Communication and Information Sharing
5-22 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Information extends HttpServlet {
public void doGet (HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException {
res.setContentType = ("text/html");
PrintWriter out = res.getWriter();
out.println
("<html><header><title>Super</title></header>");
out.println ("<body>Here is the stuff - ");
RequestDispatcher dispatch =
req.getDispatcher("/servlet/theGoods?FullName=Barry
Solomon");

/* information passed via the query string. Attributes
could have been used by setAttributes and this allows
passing in objects for more complexity. To do that, the
getDispatcher should not include the query string but do
the req.setAttribute(name, value) instead */

dispatch.include(req, res);

out.println("</body></html>");
}
}

Servlets in an Enterprise Environment

J2EE Professional Skills Development 5-23
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


Servlets in an Enterprise Environment
Enterprise brings to mind something large, integrated, scalable, and
maintainable. Enterprise servlets sustain larger projects with extra demands
and traffic.
Load Allocation and Balancing
Increasingly, Web farms and server clusters form the core of the hardware for
large-scale Web applications and distributed applications. These back-end
machines share or balance the load among themselves. If a machine fails for
any reason, the rest take up the load and it is redistributed among the
remaining machines. Servlets must be written with this sharing in mind and
these are some points to keep in mind:
• Synchronization is local and functions with the local JVM only.
• Any object within the HttpSession should be able to be relocated to
another machine. If the session moves to another machine, an unbind
event would occur on the machine that it is leaving and a binding
event would occur on the machine it has relocated to.
• Diverse instances of a servlet could be on different machines and
different JVM. Static variables and instance variables will cause
problems if used to store state—rather, store state in an external store
like a database.
• Different instances of ServletContext can exist on different machines
and in different JVM, so do not store state in the context, but store the
variables in an external storage mechanism like a database.
• Use the deployment descriptor file, web.xml, to document that the
servlet is for an enterprise situation by using an empty distributable
tag.

<web-app>
<description>
blah blah blah
</description>
<distributable/>
<context-param>
stuff
</context-param>
</web-app>
Applet-Servlet Communication and Information Sharing
5-24 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

Servlets can function within the same JVM or may execute over several
machines or a cluster. The problem with a cluster can occur within sessions as
the sessions are attached to the server they started on and the data does not
migrate. Sessions can be allowed to migrate, but the code must account for this
added functionality. Sessions can also be configured so that if one server shuts
down, the session contents have been copied and another machine ensures that
the session lives on. Most high-end environments support session migration
and session fault-tolerance to ensure continuity for their clients.
Servlets are one component within the J2EE framework, and all the pieces
must work together to have a real enterprise application. Each part or piece
should be doing what it is designed to do best whether that is messaging,
database connectivity, mail, naming, XML, or something else. Central to
making the components work together is the deployment descriptor file, the
web.xml file. Some of the entries that might be used are:
• Environment Entries or <env-entry> that the JNDI service utilizes.
• External Resource Factory or <resource-ref> is used to create other
objects from other services such as mail from the javax.mail.Session
factory or jdbc from the javax.sql.DataSource factory.
• EJB component reference or <ejb-ref> allows the servlets to get a
handle to an EJB.
The web.xml file could have all of these entries and look like the following:

<env-entry>
<env-entry-name>bucuForHire</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
</env-entry>
<resource-ref>
<res-ref-name>mail/bucuDeadMailSlot</res-ref-name>
<res-type>javax.mail.Session</res-type>
<res-auth>SERVLET</res-auth>
</resource-ref>
<ejb-ref>
<ejb-ref-name>bucuListings,/ejb-ref-name>
<ejb-ref-type>Entity</ejb-ref-type>
<home>org.loser.bucu.bucuListings</home>
<remote>org.loser.bucu.mainbucu<remote>
</ejb-ref>

Servlets in an Enterprise Environment

J2EE Professional Skills Development 5-25
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


The environmental entry can have an optional description and an entry value
for a default. The entry name is used by the JNDI lookup service and the type
is returned.
The resource reference can have an optional description. The name is used by
JNDI and the type is the resource factory used. The authentication tag reveals
who will authenticate the user: the CONTAINER or the SERVLET.
The EJB reference tag can have an optional description. Again, the name is
used by JNDI and the reference type is the type of EJB it is, either SESSION
or ENTITY. The home represents the name of the home interface and remote
is the name of the remote interface.

Applet-Servlet Communication and Information Sharing
5-26 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

Summary
• Applets and servlets can communicate via HTTP
• Applets and servlets can communicate via raw socket.
• RMI (Remote Method Invocation) can be used by a servlet to invoke
the methods of any Java object.
• RMI can use CORBA (Common Object Request Broker Architecture)
to communicate with any object written in any language.
• With RMI, the client locates the object, communicates with it, and any
external class files necessary are loaded.
• RMI consists of a remote interface, a remote object class, stubs and
skeletons, a registry, and the local objects.
• The RMI remote interface is the means by which the client interacts
with the remote object.
• The RMI object class implements the server-side methods.
• The RMI stub acts as a proxy for the remote object on the client.
• The RMI skeleton acts as a proxy for the client on the remote object.
• The RMI local objects are client-side objects that invoke the method
calls.
• A servlet running RMI is compiled and then compiled again using the
rmic command instead of javac.
• Servlets can share information or state, and can share control of a
request object.
• Servlets share information using the ServletContext object and can
utilize another Web application’s ServletContext object.
• Servlets share control of the request by either forwarding or including
with the RequestDispatcher object.
• The forward method of the RequestDispatcher sends the request to
another servlet in a transparent process to the client.
• The include method of the RequestDispatcher object places the content
of the external source inside of the calling servlet’s response like a
server-side include.
• Enterprise servlets can be set up for more robust performance and load
balancing in a server cluster or Web farm.
• Common changes made in the deployment descriptor file for
enterprise level servlets include environment entries, external resource
factory entries, and EJB component reference entries.
Servlets in an Enterprise Environment

J2EE Professional Skills Development 5-27
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


Questions
1. What are the two ways that applets and servlets can communicate?
2. True/False: Socket communication is the preferred and simpler method of
applet and servlet communication.
3. True/False: RMI exists to extend the Java object model to the network and
make the locality of the server transparent to the client.
4. What is the RMI process?
5. What is the RMI piece that acts as a representative or proxy on the client
for the remote object?
6. What is the compiling process for a servlet that will be a remote object?

Applet-Servlet Communication and Information Sharing
5-28 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

Answers
1. What are the two ways that applets and servlets can communicate?
HTTP and raw socket communication

2. True/False: Socket communication is the preferred and simpler method of
applet and servlet communication.
False

3. True/False: RMI exists to extend the Java object model to the network and
make the locality of the server transparent to the client.
True

4. What is the RMI process?
The client locates the object in the registry, it communicates and
invokes the method on the remote object, and then class files are
loaded for remote objects.

5. What is the RMI piece that acts as a representative or proxy on the client
for the remote object?
Stubs

6. What is the compiling process for a servlet that will be a remote object?
First, the class file is compiled normally by javac, then it is
compiled again using the command rmic using the name of the
servlet itself not the class file.

Servlets in an Enterprise Environment

J2EE Professional Skills Development 5-29
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


Lab 5:
Applet-Servlet
Communication
and Information
Sharing
Lab 5:
Applet-Servlet Communication and Information Sharing
5-30 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

Lab 5 Overview
In this lab you’ll learn to work with applets and servlets, and also to work with
RMI (Remote Method Invocation).
To complete this lab, you’ll need to work through two exercises:
• Working with Servlets and Applets
• Using RMI with Servlets
Each exercise includes an “Objective” section that describes the purpose of the
exercise. You are encouraged to try to complete the exercise from the
information given in the Objective section. If you require more information to
complete the exercise, the Objective section is followed by detailed step-by-
step instructions.
Working with Servlets and Applets

J2EE Professional Skills Development 5-31
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


Working with Servlets and Applets
Objective
In this exercise, you’ll use an applet on a Web page that calls on a servlet and
passes parameters into it for a result.
Things to Consider
• Setting up arrays to hold multiple parameters.
• Using the OBJECT and EMBED tags.
• Working with the PARAM tag.
• Working with the APPLET tag.
Step-by-Step Instructions
1. Open the AppletServlet.txt file in this lab’s folder.
2. Take a few minutes to examine the file. Note the following:
• There is an inner class within the file that will be compiled
when the main outer class is compiled.
• The code uses AWT and Swing, two packages to create GUI.
This applet creates a simple GUI with a button and three text
boxes for parameter input.
• An actionListener is implemented to take the button actions.
• There is really nothing in the code except for standard Java
and there is nothing that will be done in this file.
3. Close the AppletServlet.txt file and save it as AppletServlet.java.
4. Open the RequestForm.htm file in this lab’s folder.
5. There are two forms set up within this file. Set both form’s methods to
POST and their action to:

http://localhost:81/servlet/RequestForm

6. Save and close the RequestForm.htm file.
Lab 5:
Applet-Servlet Communication and Information Sharing
5-32 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

7. Open the RequestForm.txt file in this lab’s folder.
8. This will be the main servlet in this lab. Note that it has a doGet method,
which has a PrintWriter and the response is set for HTML and a basic
HTML page is begun. Set up a String to hold the number parameter from
the form and use the request’s getParameter method to retrieve this value:

String nbr = req.getParameter("number");

9. Set up a String to hold the color parameter from the form and use the
request’s getParameter method to retrieve this value (this could have
multiple values and should be a String array):

String colors[] = req.getParameterValues("colors");

10. You want the user to have feedback on the number they input on the form,
so put in appropriate header messages for the user. Also give the user
feedback on the form’s method by using the request’s getMethod method.

pw.println("<h2>You entered the following using a ");
pw.println( req.getMethod() + " method:</h2>");
pw.println("number = " + nbr + "<br />");

11. Give the user feedback on the color(s) they chose. This is an array so a
loop needs to be set up to move through the various colors and print each
color chosen.

pw.print("colors = ");
for (int i=0; i < colors.length; i++) {
pw.print(colors[i] + " ");
}
pw.println("<br />");

12. Close the HTML body and page and close the PrintWriter and the method.

pw.println("</body></html>");
pw.close();
}

Working with Servlets and Applets

J2EE Professional Skills Development 5-33
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


13. Close and save the file as RequestForm.java.
14. Open the RequestApplet.htm file in this lab’s folder.
15. Take a few minutes to examine the code. Note the following:
• The OBJECT tag is used with the Java Plug-in and its CLSID
and codebase.
• Five parameters were added, especially the ones for code and
codebase, which point to the AppletServlet class just created.
• There is an EMBEDDED tag, which is the actual applet action
and it points to the AppletServlet class and its content.
• An alternative set of tags was set up for those browsers unable
to support applets and the Java RunTime.
16. Save and close the RequestApplet.htm file.
17. Go to a command prompt and compile the program by typing:

javac RequestForm.java AppletServlet.java

18. Copy the RequestForm.class and AppletServlet.class files (found in this
lab’s folder) to the default Web application folder:

C:\JRun\servers\default\default-app\WEB-INF\classes

19. Open the Web browser and the RequestForm.htm (found in this lab’s
folder) in the browser and you should see Figure 2.
Lab 5:
Applet-Servlet Communication and Information Sharing
5-34 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


Figure 2. The RequestForm Web page.
20. Experiment with the settings and buttons.
21. Open RequestApplet.htm (found in this lab’s folder) in the Web browser
and you should see Figure 3.
Working with Servlets and Applets

J2EE Professional Skills Development 5-35
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.



Figure 3. The RequestApplet Web page.
22. Enter some values and click the SendGET button to see the results of an
applet using a servlet class.


Lab 5:
Applet-Servlet Communication and Information Sharing
5-36 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

Using RMI with Servlets
Objective
In this exercise, you’ll create a simple mechanism that allows two clients to
connect to a remote service.
Things to Consider
• Setting up the main server interface that subclasses the Remote class.
• Setting up a server implementation that subclasses the main
UnicastRemoteObject class and implements the interface just set up.
• Setting up a client implementation that connects to the server
implementation.
• Setting up the server itself with a main method that handles basic
security through a System getSecurityManager method and instantiates
the server implementation.
• Setting up the clients that instantiate the client implementation and
work with an array of interfaces.
Step-by-Step Instructions
1. There are six files involved in this lab. Two files are clients, one file is a
client implementation, a server, a server implementation and a server
interface.
2. Open the SimpleServerInterface.txt file in this lab’s folder and import
the RMI package in.

import java.rmi.*;

3. Set up the interface calling it SimpleServerInterface and have it extend
the Remote class.

public interface SimpleServerInterface extends Remote {

Using RMI with Servlets

J2EE Professional Skills Development 5-37
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


4. Set up a static String for the SERVER_NAME and set it to
"//127.0.0.1/Message_Server".

static String SERVER_NAME = "//127.0.0.1/Message_Server";

5. Set up a method called echo, passing in a string message argument to
throw a RemoteException.

String echo( String message) throws RemoteException;

6. The complete interface should have this code, be saved as
SimpleServerInterface.java, and then closed.

import java.rmi.*;

public interface SimpleServerInterface extends Remote {
static String SERVER_NAME =
"//127.0.0.1/Message_Server";

String echo( String message) throws RemoteException;

}

7. Open the SimpleServerImpl.txt file in this lab’s folder. This will be the
class to implement the interface just created above.
8. Import the RMI and RMI.server complete packages.

import java.rmi.*;
import java.rmi.server.*;

9. Set up the SimpleServerImpl class to extend UnicastRemoteObject and
implement the interface created earlier.

public class SimpleServerImpl extends UnicastRemoteObject
implements SimpleServerInterface {

Lab 5:
Applet-Servlet Communication and Information Sharing
5-38 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

10. Set up the constructor to throw a RemoteException.

public SimpleServerImpl() throws RemoteException {}

11. Set up a method called echo, passing in a string message argument to
throw a RemoteException. Have the system print out the message, return
the message String as the method result, and close the method.

public String echo( String message) throws RemoteException
{
System.out.println( "Received \"" + message + "\"
from the client");
return message;
}

12. Save the file as SimpleServerImpl.java and close it.
13. Open the SimpleClientImpl.txt file in this lab’s folder. This will be the
client implementation of the Server Interface and the RMI package needs
to be imported into it.

import java.rmi.*;

14. Set up the public class SimpleClientImpl.

public class SimpleClientImpl {

15. Set up a private static variable called server that will be a
SimpleServerInterface object.

private static SimpleServerInterface server;

16. Set up the class constructor passing in a SimpleServerInterface called
server and throwing a RemoteException.

public SimpleClientImpl( SimpleServerInterface server)
throws RemoteException {

Using RMI with Servlets

J2EE Professional Skills Development 5-39
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


17. Set the constructor’s server to the static server variable.

this.server = server;
18. Set up a String called sendMsg and put in a greeting from the client.

String sendMsg = "Hello from the client";

19. Print out to the system the message being sent from client to server.

System.out.println("Sending \""+ sendMsg +"\" to the
server");

20. Set up a String called receiveMsg to invoke the server’s echo method
passing in the String sendMsg.

String receiveMsg = server.echo(sendMsg);

21. Print out to the system the message received from the client and close the
constructor and the class.

System.out.println("Received \"" + receiveMsg + "\" from
the server");
}
}

22. Save the file as SimpleClientImpl.java and close it. The code should look
like the following:

Lab 5:
Applet-Servlet Communication and Information Sharing
5-40 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

import java.rmi.*;
public class SimpleClientImpl {

private static SimpleServerInterface server;
public SimpleClientImpl( SimpleServerInterface server)
throws RemoteException {
this.server = server;
String sendMsg = "Hello from client";
System.out.println("Sending \""+ sendMsg +"\" to the
server");
String receiveMsg = server.echo(sendMsg);
System.out.println("Received \"" + receiveMsg + "\"
from the server");
}
}

23. Open the SimpleServer.txt file in this lab’s folder.
24. Import the network and RMI packages.

import java.net.*;
import java.rmi.*;

25. Set up the class SimpleServer.

public class SimpleServer {

26. Set up a Main method.

public static void main( String[] args) {

27. Using the System’s setSecurityManager method pass in a new
RMISecurityManager object as the argument.

System.setSecurityManager( new RMISecurityManager() );

Using RMI with Servlets

J2EE Professional Skills Development 5-41
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.


28. Within a Try…Catch statement, instantiate a new SimpleServerImpl called
server.

try {
SimpleServerInterface server = new
SimpleServerImpl();

29. Using the Naming object’s rebind method, rebind the
SimpleServerInterface.SERVER_NAME to the server.

Naming.rebind( SimpleServerInterface.SERVER_NAME, server);

30. Using the System printout, inform the user that the server was bound and
started.

System.out.println( "Server bound and started");

31. Catch MalformedURLExceptions and RemoteExceptions, and provide
feedback on the errors and system exits for them. Close the try…catch, the
method, and the class.

} catch (MalformedURLException e) {
System.err.println("MalformedURLException: " + e
);
System.exit(-1);
} catch (RemoteException e) {
System.err.println("RemoteException: " + e );
System.exit(-1);
}
}
}

32. Close the file and save it as SimpleServer.java. The code should look like
the following:

Lab 5:
Applet-Servlet Communication and Information Sharing
5-42 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

import java.net.*;
import java.rmi.*;

public class SimpleServer {

public static void main( String[] args) {

System.setSecurityManager( new RMISecurityManager()
);

try {
SimpleServerInterface server = new
SimpleServerImpl();
Naming.rebind( SimpleServerInterface.SERVER_NAME,
server);
System.out.println( "Server bound and started");
} catch (MalformedURLException e) {
System.err.println("MalformedURLException: " + e
);
System.exit(-1);
} catch (RemoteException e) {
System.err.println("RemoteException: " + e );
System.exit(-1);
}
}
}

33. Open the SimpleClient.txt file in this lab’s folder.
34. Within the main method, set up a try statement (the catch portions are
already written) to create a server using the SimpleServerInterface and the
Naming (JNDI) lookup method to look up the
SimpleServerInterface.SERVER_NAME.

server = (SimpleServerInterface)Naming.lookup(
SimpleServerInterface.SERVER_NAME);

35. Set up a SimpleClientImpl called client passing in a server argument and
close the try portion of the try..catch statement.
Using RMI with Servlets

J2EE Professional Skills Development 5-43
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.



SimpleClientImpl client = new SimpleClientImpl( server);
}

36. Save the file as SimpleClient.java and close it.
37. Open the SimpleClient2.txt file in this lab’s folder.
38. Within the main method, set up a try statement (the catch portions are
already written) to create a server using the SimpleServerInterface and the
Naming (JNDI) lookup method to look up the
SimpleServerInterface.SERVER_NAME.

server = (SimpleServerInterface)Naming.lookup(
SimpleServerInterface.SERVER_NAME);

39. Set up a class array called interfaces that uses the server’s getClass method
and getInterfaces method to populate the array. Then loop through the
array and print out the interface’s names using the getName method.

Class[] interfaces = server.getClass().getInterfaces();
for (int i=0; i<interfaces.length; i++)
System.out.println(interfaces[i].getName());

40. Set up a SimpleClientImpl called client passing in a server argument and
close the try portion of the try..catch statement.

SimpleClientImpl client = new SimpleClientImpl( server);
}

41. Save the file as SimpleClient.java and close it.
42. Open a command console and type the following:

javac *.java

43. Copy all the java files to the default Web application folder:

C:\JRun\servers\default\default-app\WEB-INF\classes
Lab 5:
Applet-Servlet Communication and Information Sharing
5-44 J2EE Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

44. Run the make.bat file which has the following commands:

cls
set path=%path%;c:\rmi\tools\
set classpath=%classpath%;c:\rmi\tools\
javac *.java
rmic SimpleServerImpl
start rmiregistry
start java -Djava.security.policy=policy SimpleServer
echo "Waiting to run: java -Djava.security.policy=policy
SimpleClient"
pause
java -Djava.security.policy=policy SimpleClient

Running the make.bat file does the following:
• Sets the path for a message server.
• Compiles all the java code.
• Sets up the SimpleServerImpl to run.
• Starts the rmiregistry.
• Begins a security policy for the SimpleServer for access and for the
SimpleClient
• Closes the command console window (when you press any key as
indicated by the code, you can see, very quickly though, the message
‘Sending "Hello from client" to the server Received "Hello from
client" from the server’)
The rmiregistry is still running and now you could spend a few days setting up
a distributed application running on the RMI set up here.