Example: Running the command in the servlet

The CommandTarget interface declares one method, executeCommand, which the client implements. The executeCommand method takes a TargetableCommand object as input; it also returns a TargetableCommand.

Running the command in the servlet

The servlet that runs the command is shown in the following example. The service method retrieves the command from the input stream and runs the performExecute method on the command. The resulting object, with any output properties that must be returned to the client, is placed on the output stream and sent back to the client.

...
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.ibm.websphere.command.*;
public class CommandServlet extends HttpServlet {
...
public void service(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
try {
...
// Create input and output streams
InputStream inputStream = request.getInputStream();
OutputStream outputStream = response.getOutputStream();
// Retrieve the command from the input stream
ObjectInputStream objectInputStream =
new ObjectInputStream(inputStream);
TargetableCommand command = (TargetableCommand)
objectInputStream.readObject();
// Create the command for the return stream
Object returnObject = command;
// Try to run the command's performExecute method
try {
command.performExecute();
}
// Handle exceptions from the performExecute method
...
// Return the command with any output properties
ObjectOutputStream objectOutputStream =
new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(returnObject);
// Flush and close output streams
...
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}

The target invokes the performExecute method on the command, but this is not always necessary. In some applications, it can be preferable to implement the work of the command locally. For example, the command can be used only to send input data, so that the target retrieves the data from the command and runs a local database procedure based on the input. You must decide the appropriate way to use commands in your application.




Related tasks
Using a command
Related reference
Example: Implementing a client-side adapter
Example: Writing a command target (client-side adapter)
Reference topic Reference topic    

Terms and conditions for information centers | Feedback

Last updatedLast updated: Aug 30, 2013 6:03:36 PM CDT
http://www14.software.ibm.com/webapp/wsbroker/redirect?version=pix&product=was-base-iseries&topic=rcmd_runcmdserv
File name: rcmd_runcmdserv.html