3,InvocableServlet base class for the called servlet.
- By David Tayouri
- November 17, 2000
ENTERPRISE JAVA
Invoke Servlet Methods From Java Apps
David Tayouri
Listing 3. InvocableServlet base class for the called servlet.
/** Extend this servlet to have the ability of
method invocation.
The caller applet/application should send
the name of the method to be invoked and
a vector of the method parameters.
*/
public abstract class InvocableServlet
extends HttpServlet
{
//===========================================
/** Reads the name of method to be invoked
and its parameters from request input
stream, invokes the method and sends
the return value of the method through
response output stream. If an exception
is thrown, it is returned as output value.
*/
protected void invokeMethod(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
Object returnValue = null;
// Read name of method to be invoked and
// its params (as Vector)
ObjectInputStream in =
new ObjectInputStream(
request.getInputStream());
String methodName = null;
Vector parameters = null;
try {
methodName = (String)in.readObject();
parameters = (Vector)in.readObject();
in.close();
// Prepare param-type and param-
// value arrays (if any param)
Class paramTypes[] = null;
Object paramValues[] = null;
if ( parameters != null
&& !parameters.isEmpty()) {
paramTypes = new
Class[parameters.size()];
for (int i = 0;
i < parameters.size();
i++) {
paramTypes[i] =
parameters.elementAt(i).getClass();
// Change classes to primitive types
// See below
}
paramValues =
new Object[parameters.size()];
parameters.copyInto(paramValues);
}
// Invoke the method
Method method =
getClass().getMethod(
methodName, paramTypes);
returnValue = method.invoke(
this, paramValues);
// Exceptions are thrown in case of
// inappropriate input, method
// non-existence and illegal access
// There can be also method specific
// exceptions
} catch (Exception e) {
returnValue = e;
}
// Send the return value of the method
ObjectOutputStream out =
new ObjectOutputStream(
response.getOutputStream());
out.writeObject(returnValue);
out.close();
}
}